<?php


namespace app\api\controller;


use app\api\service\OrderService;
use app\common\controller\Api;
use think\Config;
use think\Db;
use app\common\model\Order as OrderModel;
use app\common\model\OrderProof;
use app\common\model\OrderLog;
use app\common\model\UserRoll;
use app\common\model\OrderFail;
use fast\Http;
use app\api\service\OcrService;

/**
 * 订单类
 * Class Order
 * @package app\api\controller
 */
class Order extends Api
{
// 无需登录的接口,*表示全部
    protected $noNeedLogin = ['meituanRedEnvelope','elemRedEnvelope','meituanList','cancel'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**订单列表
     * @param OrderService $orderService
     * 待上传，已完成，已取消，已超时，待审核，已驳回，已报名待下单
     */
    public function list1(OrderService $orderService)
    {
        $page = input('page/d', 1);
        $status = input('status/d', '0');
        $where = 'user_id='.$this->auth->id;
        if ($status!=0) {
            if ($status==1) {
                $where .= ' and order_status in (1,4)';// 4-美团官方活动已下单的状态
            }elseif ($status==2) {
                $where .= ' and order_status in (2,-5,6)';
            }elseif ($status==3) {
                $where .= ' and order_status in (3,-6,-7,-8,-9)';
            }elseif ($status==4) {
                $where .= ' and order_status in (1,-3,4)';
            }else{
                $where .= ' and order_status='.$status;
            }
        }
        $pageSize = 10;
        $user = Db::name('user')->where('id',$this->auth->id)->field('mobile,entry_mobile')->find();
        $sql = 'select id,create_dt,shop_name,place_time,order_status,expire_time,1 as type,is_pay,actual_rebate_amt,user_pay,update_dt,is_yunzhan,play_no,shop_no,crood_type,pay_time,proposal from chbc_play_order where '.$where.' union all select id,create_dt,shop_name,place_time,order_status,expire_time,2 as type,is_pay,actual_rebate_amt,user_pay,update_dt,is_yunzhan,play_no,shop_no,crood_type,pay_time,proposal from chbc_mtofficial_order where '.$where.' order by create_dt DESC limit '.($page-1)*$pageSize.','.$pageSize;
        $data = Db::query($sql);
        $sql = 'select count(*) as count from (select id,create_dt,shop_name,place_time,order_status,expire_time,1 as type from chbc_play_order where '.$where.' union all select id,create_dt,shop_name,place_time,order_status,expire_time,2 as type from chbc_mtofficial_order where '.$where.') a';
        $data2 = Db::query($sql);
        $count = $data2[0]['count'];
        $list = [];
        $playObj = new \app\admin\model\Play();
        foreach ($data as $key => $value) {
            if ($value['type']==1) {
                if ($value['order_status']==1 && $value['expire_time']<time()) {
                    unset($data[$key]);
                    continue;
                }
                $order = OrderModel::where('id',$value['id'])->find();
                $value['play_order_no'] = $order['is_yunzhan']==0?$order['play_order_no']:$order['yunzhan_order_no'];
                $value['poiEventId'] = '';
                if ($order['is_yunzhan']==0) {
                    $play = $playObj->where('play_no',$order['play_no'])->find();
                    $shop = \app\admin\model\Shop::where('shop_no',$order['shop_no'])->find();
                    $shop_platform = Db::name('shop_platform')->where(['shop_no'=>$shop['shop_no']])->field('qrcode_pic,platform_no,is_xls,elm_appenter')->find();
                } else {
                    $content=[];
                    if ($order['proposal']) $content = json_decode($order['proposal'],1);
                    list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($order['play_no'],$order['crood_type'],$content);
                    $value['poiEventId'] = isset($play['poiEventId'])?$play['poiEventId']:'';
                }
                $value['shop_name'] = $shop['shop_name'];
                $value['play'] = [];
                $value['play']['back_money'] = (int)$play['back_money'];
                $value['play']['back_money_text'] = $play['back_money_text'];
                $value['play']['play_type'] = $play['play_type'];
                $value['play']['img_url'] = $play['img_url'];
                $value['play']['scheme_no'] = $play['scheme_no'];
                $value['play']['scheme_no_text'] = $playObj->getSchemeNoTextAttr('',$play);
                $value['shop'] = [];
                $value['shop']['shop_name'] = $shop['shop_name'];
                $value['shop']['shop_type_text'] = $shop['shop_type_text'];
                $value['shop']['shop_type'] = isset($shop['shop_type'])?$shop['shop_type']:1;
                $value['shop']['logo_pic_url'] = $shop['logo_pic_url'];
                $value['shop']['is_xls'] = isset($shop_platform['is_xls'])?$shop_platform['is_xls']:0;
                $value['shop']['elm_appenter'] = isset($shop_platform['elm_appenter'])?$shop_platform['elm_appenter']:'';
                $value['shop']['qrcode_pic'] = isset($shop_platform['qrcode_pic'])?$shop_platform['qrcode_pic']:'';
                $value['platform_no'] = $value['shop']['platform_no'] = isset($shop_platform['platform_no'])?$shop_platform['platform_no']:'';
                $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                $value['proof'] = OrderProof::where('play_order_no',$value['play_order_no'])->order('id desc')->field('id,one_image,two_image,three_image,platform_no,wm_order_sn,supplement,handle_admin_desc,upload_time')->find();
                if ($value['order_status']==1 && $value['place_time']>0 && !$value['proof']['wm_order_sn']) {
                    $value['crood_type'] = '已报名，待下单';
                } elseif ($value['order_status']==1 && $value['place_time']>0 && isset($value['proof']['wm_order_sn']) && $value['proof']['wm_order_sn']) {
                    $value['crood_type'] = '已下单，待反馈';
                } elseif ($value['order_status']==2 || $value['order_status']==-5) {
                    $value['crood_type'] = '待审核';
                } elseif ($value['order_status']==6) {
                    $value['crood_type'] = '待商家复审';
                } elseif ($value['order_status']==-2) {
                    $value['crood_type'] = '超时取消，订单关闭';
                } elseif ($value['order_status']==-1 || $value['order_status']==-4) {
                    $value['crood_type'] = '已取消';
                } elseif ($value['order_status']==-3) {
                    $value['crood_type'] = '已驳回';
                } elseif (in_array($value['order_status'],[3,-6,-7,-8,-9])) {
                    $value['crood_type'] = '已完成';
                }
                $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                // 驳回原因
                if ($value['proof']['handle_admin_desc']) {
                    $explode = explode('（', $value['proof']['handle_admin_desc']);
                    if (isset($explode[1]) && $explode[1]) {
                        $explode = explode('）', $explode[1]);
                    }
                    if (isset($explode[0])) {
                        $value['proof']['handle_admin_desc'] = $explode[0];
                    }
                }
            } else {
                $order = \app\common\model\Mtorder::where('id',$value['id'])->find();
                if ($order['is_yunzhan']==0) {
                    $value['poiEventId'] = $order['cps_id'];
                    $value['play_order_no'] = $order['play_order_no'];
                    $value['mtofficial'] = 1;
                    $content = json_decode($order['content'],1);
                    $value['play'] = [];
                    $value['play']['back_money_text'] = isset($content['coupon_text'])?$content['coupon_text']:'';
                    $value['play']['img_url'] = isset($content['picture'])?$content['picture']:'';
                    $value['play']['wxPath'] = isset($content['actionUrl']['wxPath'])?$content['actionUrl']['wxPath']:'';
                    $value['play']['wxAppid'] = isset($content['actionUrl']['wxAppid'])?$content['actionUrl']['wxAppid']:'';
                    $value['play']['scheme_no'] = '';
                    $value['play']['scheme_no_text'] = '';
                    $platform_no = '';
                    if (isset($content['actionUrl']['wxPath']) && $content['actionUrl']['wxPath']) {
                        $wxPath = explode('?', $content['actionUrl']['wxPath']);
                        if (isset($wxPath[1]) && $wxPath[1]) {
                            $path = explode('&', $wxPath[1]);
                            foreach ($path as $p) {
                                if (strpos($p,'poi_id=')!==false) {
                                    $platform_no = ltrim($p,'poi_id=');
                                }
                                if (strpos($p,'poi_id_str=')!==false) {
                                    $platform_no .= '&'.$p;
                                }
                            }
                        }
                    }
                    $value['planActivityType'] = 1;
                    if ($order['cps_id'] && $content['poiEventId']!=$order['cps_id'] && isset($content['planActivityInfoList'])) {
                        foreach ($content['planActivityInfoList'] as $valuess) {
                            if ($order['cps_id']==$valuess['poiEventId']) {
                                $value['planActivityType'] = $valuess['planActivityType'];
                                $content['maxCommission'] = $valuess['maxCommission'];
                                $content['ratio'] = $valuess['ratio'];
                            }
                        }
                    }
                    // foreach ($content['planActivityInfoList'] as $valuess) {
                    //     if ($order['cps_id']==$valuess['poiEventId']) {
                    //         $content['maxCommission'] = $valuess['maxCommission'];
                    //         $content['ratio'] = $valuess['ratio'];
                    //     }
                    // }
                    $value['platform_no'] = $platform_no;
                    $value['shop'] = [];
                    $value['shop']['shop_name'] = isset($content['name'])?$content['name']:'';
                    $value['shop']['shop_type_text'] = '美团';
                    $value['shop']['logo_pic_url'] = isset($content['picture'])?$content['picture']:'';
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    $value['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                    if ($order['content']) {
                        $content2 = json_decode($order['content'],1);
                    }
                    if ($value['order_status']==1 && $value['pay_time']==0) {
                        $value['crood_type'] = '已报名，待下单';
                    } elseif ($value['order_status']==1 && $value['pay_time']>0) {
                        $value['crood_type'] = '已下单，待反馈';
                    } elseif ($value['order_status']==4 || $value['order_status']==-5) {
                        if ($value['is_pay']==1) {
                            $value['crood_type'] = '已下单，待完成';
                        } else {
                            $value['crood_type'] = '已下单，待评价';
                        }
                    } elseif ($value['order_status']==-2) {
                        $value['crood_type'] = '超时取消，订单关闭';
                    } elseif ($value['order_status']==-1 || $value['order_status']==-4) {
                        $value['crood_type'] = '已取消';
                    } elseif ($value['order_status']==-3) {
                        $value['crood_type'] = '已驳回';
                    } elseif (in_array($value['order_status'],[3,-6,-7,-8,-9])) {
                        $value['crood_type'] = '已完成';
                    }
                    $value['expire_time_text'] = date('Y/m/d H:i',$value['expire_time']);
                    $value['update_dt'] = date('Y/m/d H:i',strtotime($value['update_dt']));
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    // 驳回原因
                    if ($value['proof']['handle_admin_desc']) {
                        $explode = explode('（', $value['proof']['handle_admin_desc']);
                        if (isset($explode[1]) && $explode[1]) {
                            $explode = explode('）', $explode[1]);
                        }
                        if (isset($explode[0])) {
                            $value['proof']['handle_admin_desc'] = $explode[0];
                        }
                    }
                    $ratio = normal_return($content['maxCommission'],$content['ratio'])*100;
                    $value['ratio'] = $ratio;
                    $value['maxCommission'] = max_return($content['maxCommission'],$content['ratio']);
                    if ($value['user_pay']>0) {
                        $actual_rebate_amt = round($value['user_pay']*$ratio/10000,2);
                        $maxCommission = floor($value['maxCommission']/100);
                        if ($actual_rebate_amt>$maxCommission) {
                            $value['actual_rebate_amt'] = $maxCommission/100;
                        }
                    }
                } elseif (in_array($order['is_yunzhan'],[4,5])) {
                    $content = isset($order['content'])?json_decode($order['content'],1):[];
                    $content['source'] = $order['is_yunzhan'];
                    list($play,$shop) = (new \app\api\service\PlayService())->newmtofficial($order['play_no'],$order['cps_id'],$content);
                    $value['poiEventId'] = $order['cps_id'];
                    $value['play_order_no'] = $order['play_order_no'];
                    $value['mtofficial'] = 1;
                    $value['play'] = $play;
                    $value['planActivityType'] = $play['scheme_no']-1;
                    $value['platform_no'] = $shop['platform_no'];
                    $value['shop_type'] = $play['shop_type'];
                    $value['shop'] = $shop;
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    $value['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                    if ($order['content']) {
                        $content2 = json_decode($order['content'],1);
                    }
                    if ($value['order_status']==1 && $value['pay_time']==0) {
                        $value['crood_type'] = '已报名，待下单';
                    } elseif ($value['order_status']==1 && $value['pay_time']>0) {
                        $value['crood_type'] = '已下单，待反馈';
                    } elseif ($value['order_status']==4 || $value['order_status']==-5) {
                        if ($value['is_pay']==1) {
                            $value['crood_type'] = '已下单，待完成';
                        } else {
                            $value['crood_type'] = '已下单，待评价';
                        }
                    } elseif ($value['order_status']==-2) {
                        $value['crood_type'] = '超时取消，订单关闭';
                    } elseif ($value['order_status']==-1 || $value['order_status']==-4) {
                        $value['crood_type'] = '已取消';
                        if ($value['order_status']==-4) {
                            $value['proof']['handle_admin_desc'] = '订单实付金额未满足活动要求';
                        }
                    } elseif ($value['order_status']==-3) {
                        $value['crood_type'] = '已驳回';
                    } elseif (in_array($value['order_status'],[3,-6,-7,-8,-9])) {
                        $value['crood_type'] = '已完成';
                    } elseif ($value['order_status']==99) {
                        $value['crood_type'] = '审核中';
                    }
                    $value['expire_time_text'] = date('Y/m/d H:i',$value['expire_time']);
                    $value['update_dt'] = date('Y/m/d H:i',strtotime($value['update_dt']));
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    $value['ratio'] = $play['ratio'];
                    $value['maxCommission'] = $play['maxCommission'];
                    if ($value['user_pay']>0) {
                        $actual_rebate_amt = round(floatval($value['user_pay'])*floatval($value['ratio'])/100,2);
                        $maxCommission = floor($value['maxCommission']);
                        if ($actual_rebate_amt>$maxCommission) {
                            $value['actual_rebate_amt'] = $maxCommission/100;
                        }
                    }
                } else {
                    list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($order['play_no'],$order['cps_id'],json_decode($order['content'],1));
                    $value['poiEventId'] = $order['cps_id'];
                    $value['play_order_no'] = $order['play_order_no'];
                    $value['mtofficial'] = 1;
                    $value['play'] = $play;
                    $value['planActivityType'] = $play['planActivityType'];
                    $value['platform_no'] = $shop['platform_no'];
                    $value['shop'] = $shop;
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    $value['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                    if ($order['content']) {
                        $content2 = json_decode($order['content'],1);
                    }
                    if ($value['order_status']==1 && $value['pay_time']==0) {
                        $value['crood_type'] = '已报名，待下单';
                    } elseif ($value['order_status']==1 && $value['pay_time']>0) {
                        $value['crood_type'] = '已下单，待反馈';
                    } elseif ($value['order_status']==4 || $value['order_status']==-5) {
                        if ($value['is_pay']==1) {
                            $value['crood_type'] = '已下单，待完成';
                        } else {
                            $value['crood_type'] = '已下单，待评价';
                        }
                    } elseif ($value['order_status']==-2) {
                        $value['crood_type'] = '超时取消，订单关闭';
                    } elseif ($value['order_status']==-1 || $value['order_status']==-4) {
                        $value['crood_type'] = '已取消';
                    } elseif ($value['order_status']==-3) {
                        $value['crood_type'] = '已驳回';
                    } elseif (in_array($value['order_status'],[3,-6,-7,-8,-9])) {
                        $value['crood_type'] = '已完成';
                    } elseif ($value['order_status']==99) {
                        $value['crood_type'] = '审核中';
                    }
                    $value['expire_time_text'] = date('Y/m/d H:i',$value['expire_time']);
                    $value['update_dt'] = date('Y/m/d H:i',strtotime($value['update_dt']));
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    // 驳回原因
                    if ($value['proof']['handle_admin_desc']) {
                        $explode = explode('（', $value['proof']['handle_admin_desc']);
                        if (isset($explode[1]) && $explode[1]) {
                            $explode = explode('）', $explode[1]);
                        }
                        if (isset($explode[0])) {
                            $value['proof']['handle_admin_desc'] = $explode[0];
                        }
                    }
                    $value['ratio'] = $play['ratio'];
                    $value['maxCommission'] = $play['maxCommission'];
                    if ($value['user_pay']>0) {
                        $actual_rebate_amt = round($value['user_pay']*$value['ratio']/100,2);
                        $maxCommission = floor($value['maxCommission']);
                        if ($actual_rebate_amt>$maxCommission) {
                            $value['actual_rebate_amt'] = $maxCommission/100;
                        }
                    }
                }
            }
            $value['mobile'] = $order['proposal'];
            $value['source'] = $value['is_yunzhan'];
            $list[] = $value;
        }
        $last_page = ceil($count/$pageSize);
        $this->success('', ['list'=>$list,'last_page'=>$last_page, 'total' => $count]);
    }

    /**订单列表
     * @param OrderService $orderService
     * 待上传，已完成，已取消，已超时，待审核，已驳回，已报名待下单
     */
    public function list(OrderService $orderService)
    {
        $page = input('page/d', 1);
        $status = input('status/d', '0');
        $where = 'user_id='.$this->auth->id;
        if ($status!=0) {
            if ($status==1) {
                $where .= ' and order_status in (1,4)';// 4-美团官方活动已下单的状态
            }elseif ($status==2) {
                $where .= ' and order_status in (2,-5,6)';
            }elseif ($status==3) {
                $where .= ' and order_status in (3,-6,-7,-8,-9)';
            }elseif ($status==4) {
                $where .= ' and order_status in (1,-3,4)';
            }else{
                $where .= ' and order_status='.$status;
            }
        }
        $pageSize = 10;
        $user = Db::name('user')->where('id',$this->auth->id)->field('mobile,entry_mobile')->find();
        $sql = 'select id,create_dt,shop_name,place_time,order_status,expire_time,1 as type,is_pay,actual_rebate_amt,user_pay,update_dt,is_yunzhan,play_no,shop_no,crood_type,pay_time,proposal from chbc_play_order where '.$where.' union all select id,create_dt,shop_name,place_time,order_status,expire_time,2 as type,is_pay,actual_rebate_amt,user_pay,update_dt,is_yunzhan,play_no,shop_no,crood_type,pay_time,proposal from chbc_mtofficial_order where '.$where.' order by create_dt DESC limit '.($page-1)*$pageSize.','.$pageSize;
        $data = Db::query($sql);
        $sql = 'select count(*) as count from (select id,create_dt,shop_name,place_time,order_status,expire_time,1 as type from chbc_play_order where '.$where.' union all select id,create_dt,shop_name,place_time,order_status,expire_time,2 as type from chbc_mtofficial_order where '.$where.') a';
        $data2 = Db::query($sql);
        $count = $data2[0]['count'];
        $list = [];
        $playObj = new \app\admin\model\Play();
        foreach ($data as $key => $value) {
            if ($value['type']==1) {
                if ($value['order_status']==1 && $value['expire_time']<time()) {
                    unset($data[$key]);
                    continue;
                }
                $order = OrderModel::where('id',$value['id'])->find();
                $value['play_order_no'] = $order['is_yunzhan']==0?$order['play_order_no']:$order['yunzhan_order_no'];
                $value['poiEventId'] = '';
                if ($order['is_yunzhan']==0) {
                    $play = $playObj->where('play_no',$order['play_no'])->find();
                    $shop = \app\admin\model\Shop::where('shop_no',$order['shop_no'])->find();
                    $shop_platform = Db::name('shop_platform')->where(['shop_no'=>$shop['shop_no']])->field('qrcode_pic,platform_no,is_xls,elm_appenter')->find();
                } else {
                    $content=[];
                    if ($order['proposal']) $content = json_decode($order['proposal'],1);
                    list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($order['play_no'],$order['crood_type'],$content);
                    $value['poiEventId'] = isset($play['poiEventId'])?$play['poiEventId']:'';
                }
                $value['play'] = [];
                $value['play']['back_money'] = (int)$play['back_money'];
                $value['play']['back_money_text'] = $play['back_money_text'];
                $value['play']['play_type'] = $play['play_type'];
                $value['play']['img_url'] = $play['img_url'];
                $value['play']['scheme_no'] = $play['scheme_no'];
                $value['play']['scheme_no_text'] = $playObj->getSchemeNoTextAttr('',$play);
                $value['shop'] = [];
                $value['shop']['shop_name'] = $shop['shop_name'];
                $value['shop']['shop_type_text'] = $shop['shop_type_text'];
                $value['shop']['shop_type'] = isset($shop['shop_type'])?$shop['shop_type']:1;
                $value['shop']['logo_pic_url'] = $shop['logo_pic_url'];
                $value['shop']['is_xls'] = isset($shop_platform['is_xls'])?$shop_platform['is_xls']:0;
                $value['shop']['elm_appenter'] = isset($shop_platform['elm_appenter'])?$shop_platform['elm_appenter']:'';
                $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                $value['proof'] = OrderProof::where('play_order_no',$value['play_order_no'])->order('id desc')->field('id,one_image,two_image,three_image,platform_no,wm_order_sn,supplement,handle_admin_desc,upload_time')->find();
                if ($value['order_status']==1 && $value['place_time']>0 && !$value['proof']['wm_order_sn']) {
                    $value['crood_type'] = '已报名，待下单';
                } elseif ($value['order_status']==1 && $value['place_time']>0 && isset($value['proof']['wm_order_sn']) && $value['proof']['wm_order_sn']) {
                    $value['crood_type'] = '已下单，待反馈';
                } elseif ($value['order_status']==2 || $value['order_status']==-5) {
                    $value['crood_type'] = '待审核';
                } elseif ($value['order_status']==6) {
                    $value['crood_type'] = '待商家复审';
                } elseif ($value['order_status']==-2) {
                    $value['crood_type'] = '超时取消，订单关闭';
                } elseif ($value['order_status']==-1 || $value['order_status']==-4) {
                    $value['crood_type'] = '已取消';
                } elseif ($value['order_status']==-3) {
                    $value['crood_type'] = '已驳回';
                } elseif (in_array($value['order_status'],[3,-6,-7,-8,-9])) {
                    $value['crood_type'] = '已完成';
                }
                $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                // 驳回原因
                if ($value['proof']['handle_admin_desc']) {
                    $explode = explode('（', $value['proof']['handle_admin_desc']);
                    if (isset($explode[1]) && $explode[1]) {
                        $explode = explode('）', $explode[1]);
                    }
                    if (isset($explode[0])) {
                        $value['proof']['handle_admin_desc'] = $explode[0];
                    }
                }
            } else {
                $order = \app\common\model\Mtorder::where('id',$value['id'])->find();
                if ($order['is_yunzhan']==0) {
                    $value['poiEventId'] = $order['cps_id'];
                    $value['play_order_no'] = $order['play_order_no'];
                    $value['mtofficial'] = 1;
                    $content = json_decode($order['content'],1);
                    $value['play'] = [];
                    $value['play']['back_money_text'] = isset($content['coupon_text'])?$content['coupon_text']:'';
                    $value['play']['img_url'] = isset($content['picture'])?$content['picture']:'';
                    $value['play']['wxPath'] = isset($content['actionUrl']['wxPath'])?$content['actionUrl']['wxPath']:'';
                    $value['play']['wxAppid'] = isset($content['actionUrl']['wxAppid'])?$content['actionUrl']['wxAppid']:'';
                    $value['play']['scheme_no'] = '';
                    $value['play']['scheme_no_text'] = '';
                    $platform_no = '';
                    if (isset($content['actionUrl']['wxPath']) && $content['actionUrl']['wxPath']) {
                        $wxPath = explode('?', $content['actionUrl']['wxPath']);
                        if (isset($wxPath[1]) && $wxPath[1]) {
                            $path = explode('&', $wxPath[1]);
                            foreach ($path as $p) {
                                if (strpos($p,'poi_id=')!==false) {
                                    $platform_no = ltrim($p,'poi_id=');
                                }
                                if (strpos($p,'poi_id_str=')!==false) {
                                    $platform_no .= '&'.$p;
                                }
                            }
                        }
                    }
                    $value['planActivityType'] = 1;
                    if ($order['cps_id'] && $content['poiEventId']!=$order['cps_id'] && isset($content['planActivityInfoList'])) {
                        foreach ($content['planActivityInfoList'] as $valuess) {
                            if ($order['cps_id']==$valuess['poiEventId']) {
                                $value['planActivityType'] = $valuess['planActivityType'];
                                $content['maxCommission'] = $valuess['maxCommission'];
                                $content['ratio'] = $valuess['ratio'];
                            }
                        }
                    }
                    // foreach ($content['planActivityInfoList'] as $valuess) {
                    //     if ($order['cps_id']==$valuess['poiEventId']) {
                    //         $content['maxCommission'] = $valuess['maxCommission'];
                    //         $content['ratio'] = $valuess['ratio'];
                    //     }
                    // }
                    $value['platform_no'] = $platform_no;
                    $value['shop'] = [];
                    $value['shop']['shop_name'] = isset($content['name'])?$content['name']:'';
                    $value['shop']['shop_type_text'] = '美团';
                    $value['shop']['logo_pic_url'] = isset($content['picture'])?$content['picture']:'';
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    $value['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                    if ($order['content']) {
                        $content2 = json_decode($order['content'],1);
                    }
                    if ($value['order_status']==1 && $value['pay_time']==0) {
                        $value['crood_type'] = '已报名，待下单';
                    } elseif ($value['order_status']==1 && $value['pay_time']>0) {
                        $value['crood_type'] = '已下单，待反馈';
                    } elseif ($value['order_status']==4 || $value['order_status']==-5) {
                        if ($value['is_pay']==1) {
                            $value['crood_type'] = '已下单，待完成';
                        } else {
                            $value['crood_type'] = '已下单，待评价';
                        }
                    } elseif ($value['order_status']==-2) {
                        $value['crood_type'] = '超时取消，订单关闭';
                    } elseif ($value['order_status']==-1 || $value['order_status']==-4) {
                        $value['crood_type'] = '已取消';
                    } elseif ($value['order_status']==-3) {
                        $value['crood_type'] = '已驳回';
                    } elseif (in_array($value['order_status'],[3,-6,-7,-8,-9])) {
                        $value['crood_type'] = '已完成';
                    }
                    $value['expire_time_text'] = date('Y/m/d H:i',$value['expire_time']);
                    $value['update_dt'] = date('Y/m/d H:i',strtotime($value['update_dt']));
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    // 驳回原因
                    if ($value['proof']['handle_admin_desc']) {
                        $explode = explode('（', $value['proof']['handle_admin_desc']);
                        if (isset($explode[1]) && $explode[1]) {
                            $explode = explode('）', $explode[1]);
                        }
                        if (isset($explode[0])) {
                            $value['proof']['handle_admin_desc'] = $explode[0];
                        }
                    }
                    $ratio = normal_return($content['maxCommission'],$content['ratio'])*100;
                    $value['ratio'] = $ratio;
                    $value['maxCommission'] = max_return($content['maxCommission'],$content['ratio']);
                    if ($value['user_pay']>0) {
                        $actual_rebate_amt = round($value['user_pay']*$ratio/10000,2);
                        $maxCommission = floor($value['maxCommission']/100);
                        if ($actual_rebate_amt>$maxCommission) {
                            $value['actual_rebate_amt'] = $maxCommission/100;
                        }
                    }
                } elseif (in_array($order['is_yunzhan'],[4,5])) {
                    $content = isset($order['content'])?json_decode($order['content'],1):[];
                    $content['source'] = $order['is_yunzhan'];
                    list($play,$shop) = (new \app\api\service\PlayService())->newmtofficial($order['play_no'],$order['cps_id'],$content);
                    $value['poiEventId'] = $order['cps_id'];
                    $value['play_order_no'] = $order['play_order_no'];
                    $value['mtofficial'] = 1;
                    $value['play'] = $play;
                    $value['planActivityType'] = $play['scheme_no']-1;
                    $value['platform_no'] = $shop['platform_no'];
                    $value['shop_type'] = $play['shop_type'];
                    $value['shop'] = $shop;
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    $value['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                    if ($order['content']) {
                        $content2 = json_decode($order['content'],1);
                    }
                    if ($value['order_status']==1 && $value['pay_time']==0) {
                        $value['crood_type'] = '已报名，待下单';
                    } elseif ($value['order_status']==1 && $value['pay_time']>0) {
                        $value['crood_type'] = '已下单，待反馈';
                    } elseif ($value['order_status']==4 || $value['order_status']==-5) {
                        if ($value['is_pay']==1) {
                            $value['crood_type'] = '已下单，待完成';
                        } else {
                            $value['crood_type'] = '已下单，待评价';
                        }
                    } elseif ($value['order_status']==-2) {
                        $value['crood_type'] = '超时取消，订单关闭';
                    } elseif ($value['order_status']==-1 || $value['order_status']==-4) {
                        $value['crood_type'] = '已取消';
                        if ($value['order_status']==-4) {
                            $value['proof']['handle_admin_desc'] = '订单实付金额未满足活动要求';
                        }
                    } elseif ($value['order_status']==-3) {
                        $value['crood_type'] = '已驳回';
                    } elseif (in_array($value['order_status'],[3,-6,-7,-8,-9])) {
                        $value['crood_type'] = '已完成';
                    } elseif ($value['order_status']==99) {
                        $value['crood_type'] = '审核中';
                    }
                    $value['expire_time_text'] = date('Y/m/d H:i',$value['expire_time']);
                    $value['update_dt'] = date('Y/m/d H:i',strtotime($value['update_dt']));
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    $value['ratio'] = $play['ratio'];
                    $value['maxCommission'] = $play['maxCommission'];
                    if ($value['user_pay']>0) {
                        $actual_rebate_amt = round(floatval($value['user_pay'])*floatval($value['ratio'])/100,2);
                        $maxCommission = floor($value['maxCommission']);
                        if ($actual_rebate_amt>$maxCommission) {
                            $value['actual_rebate_amt'] = $maxCommission/100;
                        }
                    }
                } else {
                    list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($order['play_no'],$order['cps_id'],json_decode($order['content'],1));
                    $value['poiEventId'] = $order['cps_id'];
                    $value['play_order_no'] = $order['play_order_no'];
                    $value['mtofficial'] = 1;
                    $value['play'] = $play;
                    $value['planActivityType'] = $play['planActivityType'];
                    $value['platform_no'] = $shop['platform_no'];
                    $value['shop'] = $shop;
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    $value['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                    if ($order['content']) {
                        $content2 = json_decode($order['content'],1);
                    }
                    if ($value['order_status']==1 && $value['pay_time']==0) {
                        $value['crood_type'] = '已报名，待下单';
                    } elseif ($value['order_status']==1 && $value['pay_time']>0) {
                        $value['crood_type'] = '已下单，待反馈';
                    } elseif ($value['order_status']==4 || $value['order_status']==-5) {
                        if ($value['is_pay']==1) {
                            $value['crood_type'] = '已下单，待完成';
                        } else {
                            $value['crood_type'] = '已下单，待评价';
                        }
                    } elseif ($value['order_status']==-2) {
                        $value['crood_type'] = '超时取消，订单关闭';
                    } elseif ($value['order_status']==-1 || $value['order_status']==-4) {
                        $value['crood_type'] = '已取消';
                    } elseif ($value['order_status']==-3) {
                        $value['crood_type'] = '已驳回';
                    } elseif (in_array($value['order_status'],[3,-6,-7,-8,-9])) {
                        $value['crood_type'] = '已完成';
                    } elseif ($value['order_status']==99) {
                        $value['crood_type'] = '审核中';
                    }
                    $value['expire_time_text'] = date('Y/m/d H:i',$value['expire_time']);
                    $value['update_dt'] = date('Y/m/d H:i',strtotime($value['update_dt']));
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    // 驳回原因
                    if ($value['proof']['handle_admin_desc']) {
                        $explode = explode('（', $value['proof']['handle_admin_desc']);
                        if (isset($explode[1]) && $explode[1]) {
                            $explode = explode('）', $explode[1]);
                        }
                        if (isset($explode[0])) {
                            $value['proof']['handle_admin_desc'] = $explode[0];
                        }
                    }
                    $value['ratio'] = $play['ratio'];
                    $value['maxCommission'] = $play['maxCommission'];
                    if ($value['user_pay']>0) {
                        $actual_rebate_amt = round($value['user_pay']*$value['ratio']/100,2);
                        $maxCommission = floor($value['maxCommission']);
                        if ($actual_rebate_amt>$maxCommission) {
                            $value['actual_rebate_amt'] = $maxCommission/100;
                        }
                    }
                }
            }
            $value['mobile'] = $order['proposal'];
            $value['source'] = $value['is_yunzhan'];
            $list[] = $value;
        }
        $last_page = ceil($count/$pageSize);
        $this->success('', ['list'=>$list,'last_page'=>$last_page, 'total' => $count]);
    }

    /**订单列表
     * @param OrderService $orderService
     * 待上传，已完成，已取消，已超时，待审核，已驳回，已报名待下单
     */
    public function listbak(OrderService $orderService)
    {
        $page = input('page/d', 1);
        $status = input('status/d', '0');
        $where = 'user_id='.$this->auth->id.' and is_yunzhan=0';
        if ($status!=0) {
            if ($status==1) {
                $where .= ' and order_status in (1,4)';// 4-美团官方活动已下单的状态
            }elseif ($status==2) {
                $where .= ' and order_status in (2,-5,6)';
            }elseif ($status==3) {
                $where .= ' and order_status in (3,-6,-7,-8,-9)';
            }elseif ($status==4) {
                $where .= ' and order_status in (1,-3)';
            }else{
                $where .= ' and order_status='.$status;
            }
        }
        $pageSize = 10;
        $user = Db::name('user')->where('id',$this->auth->id)->field('mobile,entry_mobile')->find();
        $sql = 'select id,create_dt,shop_name,place_time,order_status,expire_time,1 as type,is_pay,actual_rebate_amt,user_pay,update_dt from chbc_play_order where '.$where.' union all select id,create_dt,shop_name,place_time,order_status,expire_time,2 as type,is_pay,actual_rebate_amt,user_pay,update_dt from chbc_mtofficial_order where '.$where.' order by create_dt DESC limit '.($page-1)*$pageSize.','.$pageSize;
        $data = Db::query($sql);
        $sql = 'select count(*) as count from (select id,create_dt,shop_name,place_time,order_status,expire_time,1 as type from chbc_play_order where '.$where.' union all select id,create_dt,shop_name,place_time,order_status,expire_time,2 as type from chbc_mtofficial_order where '.$where.') a';
        $data2 = Db::query($sql);
        $count = $data2[0]['count'];
        $list = [];
        $playObj = new \app\admin\model\Play();
        foreach ($data as $key => $value) {
            if ($value['type']==1) {
                if ($value['order_status']==1 && $value['expire_time']<time()) {
                    unset($data[$key]);
                    continue;
                }
                $order = OrderModel::where('id',$value['id'])->find();
                $value['play_order_no'] = $order['play_order_no'];
                $play = $playObj->where('play_no',$order['play_no'])->find();
                $value['play'] = [];
                $value['play']['back_money'] = (int)$play['back_money'];
                $value['play']['back_money_text'] = $play['back_money_text'];
                $value['play']['play_type'] = $play['play_type'];
                $value['play']['img_url'] = $play['img_url'];
                $value['play']['scheme_no'] = $play['scheme_no'];
                $value['play']['scheme_no_text'] = $playObj->getSchemeNoTextAttr('',$play);
                $shop = \app\admin\model\Shop::where('shop_no',$order['shop_no'])->find();
                $value['shop'] = [];
                $value['shop']['shop_name'] = $shop['shop_name'];
                $value['shop']['shop_type_text'] = $shop['shop_type_text'];
                $value['shop']['logo_pic_url'] = $shop['logo_pic_url'];
                $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                $value['proof'] = OrderProof::where('play_order_no',$value['play_order_no'])->order('id desc')->field('id,one_image,two_image,three_image,platform_no,wm_order_sn,supplement,handle_admin_desc,upload_time')->find();
                if ($value['order_status']==1 && $value['place_time']>0 && !$value['proof']['wm_order_sn']) {
                    $value['crood_type'] = '已报名，待下单';
                } elseif ($value['order_status']==1 && $value['place_time']>0 && isset($value['proof']['wm_order_sn']) && $value['proof']['wm_order_sn']) {
                    $value['crood_type'] = '已下单，待反馈';
                } elseif ($value['order_status']==2 || $value['order_status']==-5) {
                    $value['crood_type'] = '待审核';
                } elseif ($value['order_status']==6) {
                    $value['crood_type'] = '待商家复审';
                } elseif ($value['order_status']==-2) {
                    $value['crood_type'] = '超时取消，订单关闭';
                } elseif ($value['order_status']==-1 || $value['order_status']==-4) {
                    $value['crood_type'] = '已取消';
                } elseif ($value['order_status']==-3) {
                    $value['crood_type'] = '已驳回';
                } elseif (in_array($value['order_status'],[3,-6,-7,-8,-9])) {
                    $value['crood_type'] = '已完成';
                }
                $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                // 驳回原因
                if ($value['proof']['handle_admin_desc']) {
                    $explode = explode('（', $value['proof']['handle_admin_desc']);
                    if (isset($explode[1]) && $explode[1]) {
                        $explode = explode('）', $explode[1]);
                    }
                    if (isset($explode[0])) {
                        $value['proof']['handle_admin_desc'] = $explode[0];
                    }
                }
            } else {
                $order = \app\common\model\Mtorder::where('id',$value['id'])->find();
                $value['play_order_no'] = $order['play_order_no'];
                $value['mtofficial'] = 1;
                // $mtofficial = Db::name('mtofficial')->where(['no'=>$order['play_no']])->order('id DESC')->find();
                $content = json_decode($order['content'],1);
                $value['play'] = [];
                $value['play']['back_money_text'] = isset($content['coupon_text'])?$content['coupon_text']:'';
                $value['play']['img_url'] = $content['picture'];
                $value['play']['wxPath'] = isset($content['actionUrl']['wxPath'])?$content['actionUrl']['wxPath']:'';
                $value['play']['wxAppid'] = isset($content['actionUrl']['wxAppid'])?$content['actionUrl']['wxAppid']:'';
                $value['play']['scheme_no'] = '';
                $value['play']['scheme_no_text'] = '';
                $platform_no = '';
                if (isset($content['actionUrl']['wxPath']) && $content['actionUrl']['wxPath']) {
                    $wxPath = explode('?', $content['actionUrl']['wxPath']);
                    if (isset($wxPath[1]) && $wxPath[1]) {
                        $path = explode('&', $wxPath[1]);
                        foreach ($path as $p) {
                            if (strpos($p,'poi_id=')!==false) {
                                $platform_no = ltrim($p,'poi_id=');
                            }
                            if (strpos($p,'poi_id_str=')!==false) {
                                $platform_no .= '&'.$p;
                            }
                        }
                    }
                }
                $value['planActivityType'] = 1;
                if ($order['cps_id'] && $content['poiEventId']!=$order['cps_id'] && isset($content['planActivityInfoList'])) {
                    foreach ($content['planActivityInfoList'] as $valuess) {
                        if ($order['cps_id']==$valuess['poiEventId']) {
                            $value['planActivityType'] = $valuess['planActivityType'];
                            $content['maxCommission'] = $valuess['maxCommission'];
                            $content['ratio'] = $valuess['ratio'];
                        }
                    }
                }
                // foreach ($content['planActivityInfoList'] as $valuess) {
                //     if ($order['cps_id']==$valuess['poiEventId']) {
                //         $content['maxCommission'] = $valuess['maxCommission'];
                //         $content['ratio'] = $valuess['ratio'];
                //     }
                // }
                $value['platform_no'] = $platform_no;
                $value['shop'] = [];
                $value['shop']['shop_name'] = $content['name'];
                $value['shop']['shop_type_text'] = '美团';
                $value['shop']['logo_pic_url'] = $content['picture'];
                $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                $value['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                if ($order['content']) {
                    $content2 = json_decode($order['content'],1);
                }
                if ($value['order_status']==1 && $value['place_time']>0) {
                    $value['crood_type'] = '已报名，待下单';
                } elseif ($value['order_status']==1 && $value['place_time']>0 && isset($content2['code']) && $content2['code']==3) {
                    $value['crood_type'] = '已报名，待下单';
                } elseif ($value['order_status']==1 && $value['place_time']>0 && isset($content2['code']) && $content2['code']==4) {
                    $value['crood_type'] = '已下单，待反馈';
                } elseif ($value['order_status']==4 || $value['order_status']==-5) {
                    if ($value['is_pay']==1) {
                        $value['crood_type'] = '已下单，待完成';
                    } else {
                        $value['crood_type'] = '已下单，待评价';
                    }
                } elseif ($value['order_status']==-2) {
                    $value['crood_type'] = '超时取消，订单关闭';
                } elseif ($value['order_status']==-1 || $value['order_status']==-4) {
                    $value['crood_type'] = '已取消';
                } elseif ($value['order_status']==-3) {
                    $value['crood_type'] = '已驳回';
                } elseif (in_array($value['order_status'],[3,-6,-7,-8,-9])) {
                    $value['crood_type'] = '已完成';
                }
                $value['expire_time_text'] = date('Y/m/d H:i',$value['expire_time']);
                $value['update_dt'] = date('Y/m/d H:i',strtotime($value['update_dt']));
                $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                // 驳回原因
                if ($value['proof']['handle_admin_desc']) {
                    $explode = explode('（', $value['proof']['handle_admin_desc']);
                    if (isset($explode[1]) && $explode[1]) {
                        $explode = explode('）', $explode[1]);
                    }
                    if (isset($explode[0])) {
                        $value['proof']['handle_admin_desc'] = $explode[0];
                    }
                }
                $ratio = normal_return($content['maxCommission'],$content['ratio'])*100;
                $value['ratio'] = $ratio;
                $value['maxCommission'] = max_return($content['maxCommission'],$content['ratio']);
                if ($value['user_pay']>0) {
                    $actual_rebate_amt = round($value['user_pay']*$ratio/10000,2);
                    $maxCommission = floor($value['maxCommission']/100);
                    if ($actual_rebate_amt>$maxCommission) {
                        $value['actual_rebate_amt'] = $maxCommission/100;
                    }
                }
            }
            $value['mobile'] = $order['proposal'];
            $list[] = $value;
        }
        $last_page = ceil($count/$pageSize);
        $this->success('', ['list'=>$list,'last_page'=>$last_page, 'total' => $count]);
    }


    /**
     * 提交单号锁定名额
     * @DateTime 2023-04-02T19:28:35+0800
     * @return   [type]                   [description]
     */
    public function reserve1()
    {
        //外卖单号
        $wm_order_sn = input('wm_order_sn', '','htmlspecialchars,htmlentities');
        $poiEventId = input('poiEventId', '','');
        $wm_order_sn = trim($wm_order_sn);
        $poiEventId = trim($poiEventId);
        $wm_order_sn = str_replace(' ', '', $wm_order_sn);  // 当前平台订单id
        if (!$wm_order_sn) {
            $this->error('请上传正确单号');
        }
        if (!is_numeric($wm_order_sn) || !\think\Validate::is($wm_order_sn, '\S{18,30}')) {
            $this->error('单号格式不对');
        }

        $play_order_no = input('play_order_no', '','htmlspecialchars,htmlentities'); 
        if ($poiEventId && $poiEventId!='undefined' && $poiEventId!='null') {
            $order = OrderModel::where('yunzhan_order_no',$play_order_no)->find();
        } else {
            $order = OrderModel::where('play_order_no',$play_order_no)->find();
        }
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order['order_status']!=1) {
            $this->error('订单状态有误');
        }
        // $play = (new \app\admin\model\Play())->where(['play_no' => $order->play_no])->find();
        // if (!$play) {
        //     $this->error('活动不存在');
        // }
        // 是否超过30分钟
        if (time()>$order['expire_time']) {
            $this->error('超过1小时未上传单号，订单已过期');
        }
        // 同一订单号提交过后不可重复提交
        $snNUm = OrderModel::where([
            'wm_order_sn'=>$wm_order_sn,
            'order_status' => ['in',[1,2,3,-3,-5,-6,-7,-8,-9]]
        ])->find();
        if (count($snNUm)>0) {
            $this->error('该外卖单号已使用过');
        }
        Db::startTrans();
        try {
            // $order->expire_time = time()+intval(config('proof_expire')); // 6hour
            $order->expire_time = strtotime(date('Ymd',$order['place_time']))+129600; // 明天中午12
            $order->wm_order_sn = $wm_order_sn;
            $order->save();
            $OrderProof = new OrderProof();
            $data = [
                'wm_order_sn' => $wm_order_sn,
                // 'merchant_id' => $play['user_id'],
                'shop_no' => $order['shop_no'],
                'user_id' => $order['user_id'],
                'play_order_no' => $play_order_no,
                'platform_no' => $order['platform_no'],
                'user_pay' => $order['user_pay'],      // 满多少
                'back_money' => $order['actual_rebate_amt'] //返多少
            ];
            $OrderProof->allowField(true)->save($data);
            // orderlog
            OrderLog::create([
                'play_order_id' => $order['id'],
                // 'play_order_no' => $order['yunzhan_order_no'],
                'create_by' => $this->auth->nickname,
                'create_by_id' => $this->auth->id,
                'is_front' => 1,
                'info' => '提交单号',
            ]);
            if ($poiEventId && $poiEventId!='undefined' && $poiEventId!='null') {
                $bwc = new \services\BwcService();
                $res = $bwc->confirmOrder($play_order_no,$this->auth->mobile,$wm_order_sn);
                // $res = '{"status":true,"code":200,"message":"success","data":true}';
                \think\Log::write('回填单号exception1=>'.$res);
                $decode = json_decode($res,1);
                if ($decode['status']!=true) {
                    $this->error($decode['message']);
                }
            }
            Db::commit();
            $this->success('单号提交成功，请尽快提交下单凭证');
        } catch (Exception $e) {
            \think\Log::write('提交单号：Exception=>'.$e->getMessage(), 'error');
            Db::rollback();
            $this->error('提交单号失败');
        }   
    }


    /**
     * 提交单号锁定名额
     * @DateTime 2023-04-02T19:28:35+0800
     * @return   [type]                   [description]
     */
    public function reserve()
    {
        //外卖单号
        $wm_order_sn = input('wm_order_sn', '','htmlspecialchars,htmlentities');
        $wm_order_sn = trim($wm_order_sn);
        $wm_order_sn = str_replace(' ', '', $wm_order_sn);  // 当前平台订单id
        if (!$wm_order_sn) {
            $this->error('请上传正确单号');
        }
        if (!is_numeric($wm_order_sn) || !\think\Validate::is($wm_order_sn, '\S{18,30}')) {
            $this->error('单号格式不对');
        }

        $play_order_no = input('play_order_no', '','htmlspecialchars,htmlentities'); 
        $order = OrderModel::where('play_order_no',$play_order_no)->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order['order_status']!=1) {
            $this->error('订单状态有误');
        }
        $play = (new \app\admin\model\Play())->where(['play_no' => $order->play_no])->find();
        if (!$play) {
            $this->error('活动不存在');
        }
        // 是否超过30分钟
        if (time()>$order['expire_time']) {
            $this->error('超过1小时未上传单号，订单已过期');
        }
        // 同一订单号提交过后不可重复提交
        $snNUm = OrderModel::where([
            'wm_order_sn'=>$wm_order_sn,
            'order_status' => ['in',[1,2,3,-3,-5,-6,-7,-8,-9]]
        ])->find();
        if (count($snNUm)>0) {
            $this->error('该外卖单号已使用过');
        }
        Db::startTrans();
        try {
            // $order->expire_time = time()+intval(config('proof_expire')); // 6hour
            $order->expire_time = strtotime(date('Ymd',$order['place_time']))+129600; // 明天中午12
            $order->wm_order_sn = $wm_order_sn;
            $order->save();
            $OrderProof = new OrderProof();
            $data = [
                'wm_order_sn' => $wm_order_sn,
                'merchant_id' => $play['user_id'],
                'shop_no' => $order['shop_no'],
                'user_id' => $order['user_id'],
                'play_order_no' => $order['play_order_no'],
                'platform_no' => $order['platform_no'],
                'user_pay' => $order['user_pay'],      // 满多少
                'back_money' => $order['actual_rebate_amt'] //返多少
            ];
            $OrderProof->allowField(true)->save($data);
            // orderlog
            OrderLog::create([
                'play_order_id' => $order['id'],
                'play_order_no' => $order['play_order_no'],
                'create_by' => $this->auth->nickname,
                'create_by_id' => $this->auth->id,
                'is_front' => 1,
                'info' => '提交单号',
            ]);
            Db::commit();
            $this->success('单号提交成功，请尽快提交下单凭证');
        } catch (Exception $e) {
            \think\Log::write('提交单号：Exception=>'.$e->getMessage(), 'error');
            Db::rollback();
            $this->error('提交单号失败');
        }   
    }


    /**
     * 是否具备下单条件
     * @return [type] [description]
     */
    public function validateOder1()
    {
        $poiEventId = input('poiEventId', '');
        $address = input('address', '');
        $is_leading = input('is_leading/d', 0); // 是否超前抢单
        $userId = $this->auth->id;
        if ($poiEventId) {
            $play_no = input('id', '');
            //活动检测
            $user = (new \app\common\model\User())->where(['id'=> $userId,'user_type'=>2,'status'=>'normal'])->find();
            if (!$user) $this->error('该账号暂不能报名');
            if (!$user->mobile) $this->error('请先绑定手机号');
            list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($play_no,$poiEventId);
            if ($user['xzxd']==1 && $play['scheme_no']!=3) {
                $this->error('无法参与该活动');
            }
            if (empty($play) || $play['stock'] <= 0) $this->error('活动名额已满');
            $userorder = order_count_read($userId);
            if ($userorder<6) {
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'create_dt' => ['>=',date('Y-m-d',time())],
                    'order_status' => ['not in',[-1,-2,-4]]
                ])->count();
                if ($orderNum >= 2) $this->error('您的报名次数已用完');
            } else {
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'create_dt' => ['>=',date('Y-m-d',time())],
                    'order_status' => ['not in',[-1,-2,-4]]
                ])->count();
                if ($orderNum >= 5) $this->error('您的报名次数已用完');
            }

            // 用户是否存在未完成的异常订单和未完成的不满意反馈订单
            $orderNum = Db::name('play_order')->where([
                'user_id' => $userId,
                'order_status' => -5
            ])->count();
            if ($orderNum) {
                $this->error('您好，您当前有一笔“我要反馈”订单正在处理中，需等该笔订单完成后才能继续参加返利活动哦~');
            }
            $orderNum = Db::name('play_order')->where([
                'user_id' => $userId,
                'order_status' => ['in',[-7,-8]]
            ])->field('play_order_no')->find();
            if ($orderNum) {
                $proof = Db::name('play_order_proof')->where('play_order_no',$orderNum['play_order_no'])->order('id DESC')->value('handle_merchant_desc');
                $handle_merchant_desc = json_decode($proof,1);
                if (isset($handle_merchant_desc['desc'])) {
                    $this->error('宝子，商家反映您目前有一笔订单存在“异常类型：'.$handle_merchant_desc['desc'].'”请联系客服处理完才能继续参与返利活动哦~~');
                } else {
                    $this->error('宝子，商家反映您目前有一笔订单存在异常，请联系客服处理完才能继续参与返利活动哦~~');
                }
            } 
        } else {
            $play_no = input('play_no', '');
            //活动检测
            $user = (new \app\common\model\User())->where(['id'=> $userId,'user_type'=>2,'status'=>'normal'])->find();
            if (!$user) $this->error('该账号暂不能报名');
            if (!$user->mobile) $this->error('请先绑定手机号');

            //活动检测
            $play = (new \app\admin\model\Play())->where('play_no', $play_no)->find();
            if ($user['xzxd']==1 && $play['scheme_no']!=3) {
                $this->error('无法参与该活动');
            }
            if (empty($play) || $play['stock'] <= 0) $this->error('活动名额已满');
            if ($play['start_date'] > time() || $play['end_date'] < time()) $this->error('不在活动时间内');
            if ($play['play_status'] != 2) $this->error('活动未开始或已完结');

            $orderNum = (new \app\common\model\Order())->where([
                'user_id' => $userId,
                'shop_no' => $play['shop_no'],
                'order_status' => ['in',[1,2,-3,-5]]
            ])->count();
            if ($orderNum) {
                $this->error('您已经报名过该店铺的活动，请先完成当前未完成的订单');
            }
            // 如果是新用户专享，只能新用户报名
            // $olduser = Db::name('play_order')->where(['user_id'=>$userId,'order_status'=>['in',[3,-6,-7,-8,-9,-4]]])->count();
            $olduser = order_count_read($userId);
            if ($play['play_label']==2 && $olduser) {
                $this->error('您不是新用户，不能报名新用户专享活动');
            }
            // 华东师范大学(中山北路校区) 的新用户限制下单
            // if (!$olduser && $address=='华东师范大学(中山北路校区)') {
            //     $this->error('无法参与该活动');
            // }
            // 是否有大牌专享券
            $play_label = 0;
            $config = config('site.play_label');
            if (count($config)) {
                foreach ($config as $keys => $values) {
                    if ($values=='大牌专享') {
                        $play_label = $keys;
                    }
                }
            }
            $roll = [];
            // 是大牌专享活动就使用大牌专享券，否则使用饭票
            if ($play_label>0 && $play['play_label']==$play_label) {
                $roll = UserRoll::where(['roll_type'=>'card_three','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
                $error = '您没有大牌专享券，抢单失败';
            } else {
                $roll = UserRoll::where(['roll_type'=>'card_four','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
                $error = '您没有饭票，抢单失败';
            }
            if (!$roll) {
                $this->error($error);
            }
            // 是否超前抢单
            $roll2 = [];
            if ($is_leading) {
                // 是否在活动开始前30分钟
                $start_time_str = strtotime(date('Ymd').' '.$play['start_time_str']);
                if (time()<$start_time_str && time()>=$start_time_str-1800) {
                    $roll2 = UserRoll::where(['roll_type'=>'card_one','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
                    if (!$roll2) {
                        $this->error('您没有超前抢单券，抢单失败');
                    }
                } else {
                    $this->error('超前抢单券不可用，抢单失败');
                }
            } else {
                // 判断是不是活动时间
                $start_time_str = strtotime(date('Ymd').' '.$play['start_time_str']);
                $end_time_str = strtotime(date('Ymd').' '.$play['end_time_str']);
                if (time()<$start_time_str || time()>$end_time_str) {
                    $this->error('不在活动时间内');
                }
            }
            // 下单限制
            if ($play['times_limit']==1 && $play['jt']>1 && $play['jc']>0) {
                // 过去几天
                $thisday = date('Y-m-d H:i:s',strtotime(date('Ymd'))-($play['jt']-1)*86400);
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'shop_no' => $play['shop_no'],
                    'order_status' => ['not in', [-1, -2, -4]],
                    'create_dt' => ['>',$thisday]
                ])->count();
                if ($orderNum >= $play['jc']) $this->error('该活动商家限制'.$play['jt'].'天只能参加'.$play['jc'].'次');
            } elseif ($play['times_limit']==1 && $play['jt']==1 && $play['jc']>0) {
                // 过去几天
                $thisday = date('Y-m-d H:i:s',strtotime(date('Ymd'))-($play['jt']-1)*86400);
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'shop_no' => $play['shop_no'],
                    'order_status' => ['not in', [-1, -2, -4]],
                    'create_dt' => ['>',$thisday]
                ])->count();
                if ($orderNum >= $play['jc']) $this->error('该活动商家限制'.$play['jt'].'天只能参加'.$play['jc'].'次');
            }
            //下单限制检测，每天只能报名一次
            // $thisday = date('Y-m-d',time());
            // $orderNum = (new \app\common\model\Order())->where([
            //     'user_id' => $userId,
            //     'shop_no' => $play['shop_no'],
            //     'order_status' => ['not in', [-1, -2, -4]],
            //     'create_dt' => ['>',$thisday]
            // ])->count();
            // if ($orderNum >= 1) $this->error('该店铺活动每天只能参加一次哦，试试其他的活动吧~');
            // // 每周只能报名三次
            // $thisweek = time()-86400*7;
            // $orderNum = (new \app\common\model\Order())->where([
            //     'user_id' => $userId,
            //     'shop_no' => $play['shop_no'],
            //     'order_status' => ['not in', [-1, -2, -4]],
            //     'create_dt' => ['>',date('Y-m-d H:i:s',$thisweek)]
            // ])->count();
            // if ($orderNum >= 3) $this->error('该店铺活动每周只能参加三次哦，试试其他的活动吧~');
           
            // 同一个用户同一家店铺两个小时内只能报名一个订单
            // $orderNum = (new \app\common\model\Order())->where([
            //     'user_id' => $userId,
            //     'shop_no' => $play['shop_no'],
            //     'create_dt' => ['>',date('Y-m-d H:i:s',(time()-7200))]
            // ])->count();
            // if ($orderNum >= 1) $this->error('同一个用户同一家店铺两个小时内只能报名一个订单');
            // 用户完成订单小于6单时，一天最多只能完成2单，用户完成订单大于6单时，一天最多只能完成5单
            $userorder = order_count_read($userId);
            if ($userorder<6) {
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'create_dt' => ['>=',date('Y-m-d',time())],
                    'order_status' => ['not in',[-1,-2,-4]]
                ])->count();
                if ($orderNum >= 2) $this->error('您的报名次数已用完');
            } else {
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'create_dt' => ['>=',date('Y-m-d',time())],
                    'order_status' => ['not in',[-1,-2,-4]]
                ])->count();
                if ($orderNum >= 5) $this->error('您的报名次数已用完');
            }
            // 店铺是否禁止用户下单
            $shop = Db::name('shop')->where(['shop_no'=>$play['shop_no']])->field('limited_user')->find();
            if ($shop['limited_user']) {
                $limited_user = trim($shop['limited_user'],'|');
                $limited_user_arr = explode('|', $limited_user);
                if (count($limited_user_arr) && in_array($this->auth->id, $limited_user_arr)) {
                    $this->error('您已超出该店铺点餐次数上限');
                }
            }

            // 用户是否存在未完成的异常订单和未完成的不满意反馈订单
            $orderNum = Db::name('play_order')->where([
                'user_id' => $userId,
                'order_status' => -5
            ])->count();
            if ($orderNum) {
                $this->error('您好，您当前有一笔“我要反馈”订单正在处理中，需等该笔订单完成后才能继续参加返利活动哦~');
            }
            $orderNum = Db::name('play_order')->where([
                'user_id' => $userId,
                'order_status' => ['in',[-7,-8]]
            ])->field('play_order_no')->find();
            if ($orderNum) {
                $proof = Db::name('play_order_proof')->where('play_order_no',$orderNum['play_order_no'])->order('id DESC')->value('handle_merchant_desc');
                $handle_merchant_desc = json_decode($proof,1);
                if (isset($handle_merchant_desc['desc'])) {
                    $this->error('宝子，商家反映您目前有一笔订单存在“异常类型：'.$handle_merchant_desc['desc'].'”请联系客服处理完才能继续参与返利活动哦~~');
                } else {
                    $this->error('宝子，商家反映您目前有一笔订单存在异常，请联系客服处理完才能继续参与返利活动哦~~');
                }
            } 
        }
        $this->success('满足下单条件');
    }


    /**
     * 是否具备下单条件
     * @return [type] [description]
     */
    public function validateOder()
    {
        $play_no = input('play_no', '');
        $address = input('address', '');
        $is_leading = input('is_leading/d', 0); // 是否超前抢单
        $userId = $this->auth->id;
        //活动检测
        $user = (new \app\common\model\User())->where(['id'=> $userId,'user_type'=>2,'status'=>'normal'])->find();
        if (!$user) $this->error('该账号暂不能报名');
        if (!$user->mobile) $this->error('请先绑定手机号');

        //活动检测
        $play = (new \app\admin\model\Play())->where('play_no', $play_no)->find();
        if ($user['xzxd']==1 && $play['scheme_no']!=3) {
            $this->error('无法参与该活动');
        }
        if (empty($play) || $play['stock'] <= 0) $this->error('活动名额已满');
        if ($play['start_date'] > time() || $play['end_date'] < time()) $this->error('不在活动时间内');
        if ($play['play_status'] != 2) $this->error('活动未开始或已完结');

        $orderNum = (new \app\common\model\Order())->where([
            'user_id' => $userId,
            'shop_no' => $play['shop_no'],
            'order_status' => ['in',[1,2,-3,-5]]
        ])->count();
        if ($orderNum) {
            $this->error('您已经报名过该店铺的活动，请先完成当前未完成的订单');
        }
        // 如果是新用户专享，只能新用户报名
        // $olduser = Db::name('play_order')->where(['user_id'=>$userId,'order_status'=>['in',[3,-6,-7,-8,-9,-4]]])->count();
        $olduser = order_count_read($userId);
        if ($play['play_label']==2 && $olduser) {
            $this->error('您不是新用户，不能报名新用户专享活动');
        }
        // 华东师范大学(中山北路校区) 的新用户限制下单
        // if (!$olduser && $address=='华东师范大学(中山北路校区)') {
        //     $this->error('无法参与该活动');
        // }
        // 是否有大牌专享券
        $play_label = 0;
        $config = config('site.play_label');
        if (count($config)) {
            foreach ($config as $keys => $values) {
                if ($values=='大牌专享') {
                    $play_label = $keys;
                }
            }
        }
        $roll = [];
        // 是大牌专享活动就使用大牌专享券，否则使用饭票
        if ($play_label>0 && $play['play_label']==$play_label) {
            $roll = UserRoll::where(['roll_type'=>'card_three','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
            $error = '您没有大牌专享券，抢单失败';
        } else {
            $roll = UserRoll::where(['roll_type'=>'card_four','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
            $error = '您没有饭票，抢单失败';
        }
        if (!$roll) {
            $this->error($error);
        }
        // 是否超前抢单
        $roll2 = [];
        if ($is_leading) {
            // 是否在活动开始前30分钟
            $start_time_str = strtotime(date('Ymd').' '.$play['start_time_str']);
            if (time()<$start_time_str && time()>=$start_time_str-1800) {
                $roll2 = UserRoll::where(['roll_type'=>'card_one','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
                if (!$roll2) {
                    $this->error('您没有超前抢单券，抢单失败');
                }
            } else {
                $this->error('超前抢单券不可用，抢单失败');
            }
        } else {
            // 判断是不是活动时间
            $start_time_str = strtotime(date('Ymd').' '.$play['start_time_str']);
            $end_time_str = strtotime(date('Ymd').' '.$play['end_time_str']);
            if (time()<$start_time_str || time()>$end_time_str) {
                $this->error('不在活动时间内');
            }
        }
        // 下单限制
        if ($play['times_limit']==1 && $play['jt']>1 && $play['jc']>0) {
            // 过去几天
            $thisday = date('Y-m-d H:i:s',strtotime(date('Ymd'))-($play['jt']-1)*86400);
            $orderNum = (new \app\common\model\Order())->where([
                'user_id' => $userId,
                'shop_no' => $play['shop_no'],
                'order_status' => ['not in', [-1, -2, -4]],
                'create_dt' => ['>',$thisday]
            ])->count();
            if ($orderNum >= $play['jc']) $this->error('该活动商家限制'.$play['jt'].'天只能参加'.$play['jc'].'次');
        } elseif ($play['times_limit']==1 && $play['jt']==1 && $play['jc']>0) {
            // 过去几天
            $thisday = date('Y-m-d H:i:s',strtotime(date('Ymd'))-($play['jt']-1)*86400);
            $orderNum = (new \app\common\model\Order())->where([
                'user_id' => $userId,
                'shop_no' => $play['shop_no'],
                'order_status' => ['not in', [-1, -2, -4]],
                'create_dt' => ['>',$thisday]
            ])->count();
            if ($orderNum >= $play['jc']) $this->error('该活动商家限制'.$play['jt'].'天只能参加'.$play['jc'].'次');
        }
        //下单限制检测，每天只能报名一次
        // $thisday = date('Y-m-d',time());
        // $orderNum = (new \app\common\model\Order())->where([
        //     'user_id' => $userId,
        //     'shop_no' => $play['shop_no'],
        //     'order_status' => ['not in', [-1, -2, -4]],
        //     'create_dt' => ['>',$thisday]
        // ])->count();
        // if ($orderNum >= 1) $this->error('该店铺活动每天只能参加一次哦，试试其他的活动吧~');
        // // 每周只能报名三次
        // $thisweek = time()-86400*7;
        // $orderNum = (new \app\common\model\Order())->where([
        //     'user_id' => $userId,
        //     'shop_no' => $play['shop_no'],
        //     'order_status' => ['not in', [-1, -2, -4]],
        //     'create_dt' => ['>',date('Y-m-d H:i:s',$thisweek)]
        // ])->count();
        // if ($orderNum >= 3) $this->error('该店铺活动每周只能参加三次哦，试试其他的活动吧~');
       
        // 同一个用户同一家店铺两个小时内只能报名一个订单
        // $orderNum = (new \app\common\model\Order())->where([
        //     'user_id' => $userId,
        //     'shop_no' => $play['shop_no'],
        //     'create_dt' => ['>',date('Y-m-d H:i:s',(time()-7200))]
        // ])->count();
        // if ($orderNum >= 1) $this->error('同一个用户同一家店铺两个小时内只能报名一个订单');
        // 用户完成订单小于6单时，一天最多只能完成2单，用户完成订单大于6单时，一天最多只能完成5单
        $userorder = order_count_read($userId);
        if ($userorder<6) {
            $orderNum = (new \app\common\model\Order())->where([
                'user_id' => $userId,
                'create_dt' => ['>=',date('Y-m-d',time())],
                'order_status' => ['not in',[-1,-2,-4]]
            ])->count();
            if ($orderNum >= 2) $this->error('您的报名次数已用完');
        } else {
            $orderNum = (new \app\common\model\Order())->where([
                'user_id' => $userId,
                'create_dt' => ['>=',date('Y-m-d',time())],
                'order_status' => ['not in',[-1,-2,-4]]
            ])->count();
            if ($orderNum >= 5) $this->error('您的报名次数已用完');
        }
        // 店铺是否禁止用户下单
        $shop = Db::name('shop')->where(['shop_no'=>$play['shop_no']])->field('limited_user')->find();
        if ($shop['limited_user']) {
            $limited_user = trim($shop['limited_user'],'|');
            $limited_user_arr = explode('|', $limited_user);
            if (count($limited_user_arr) && in_array($this->auth->id, $limited_user_arr)) {
                $this->error('您已超出该店铺点餐次数上限');
            }
        }

        // 用户是否存在未完成的异常订单和未完成的不满意反馈订单
        $orderNum = Db::name('play_order')->where([
            'user_id' => $userId,
            'order_status' => -5
        ])->count();
        if ($orderNum) {
            $this->error('您好，您当前有一笔“我要反馈”订单正在处理中，需等该笔订单完成后才能继续参加返利活动哦~');
        }
        $orderNum = Db::name('play_order')->where([
            'user_id' => $userId,
            'order_status' => ['in',[-7,-8]]
        ])->field('play_order_no')->find();
        if ($orderNum) {
            $proof = Db::name('play_order_proof')->where('play_order_no',$orderNum['play_order_no'])->order('id DESC')->value('handle_merchant_desc');
            $handle_merchant_desc = json_decode($proof,1);
            if (isset($handle_merchant_desc['desc'])) {
                $this->error('宝子，商家反映您目前有一笔订单存在“异常类型：'.$handle_merchant_desc['desc'].'”请联系客服处理完才能继续参与返利活动哦~~');
            } else {
                $this->error('宝子，商家反映您目前有一笔订单存在异常，请联系客服处理完才能继续参与返利活动哦~~');
            }
        } 
        $this->success('满足下单条件');
    }

    /**
     * 报名
     * @param OrderService $orderService
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function createOrder1()
    {
        $is_validate = input('is_validate',0);
        $poiEventId = input('poiEventId', '');
        $address = input('address', '');
        $is_leading = input('is_leading/d', 0); // 是否超前抢单
        $userId = $this->auth->id;
        if ($poiEventId) {
            $play_no = input('id', '');
            $roll = [];
            // 是大牌专享活动就使用大牌专享券，否则使用饭票
            $roll = UserRoll::where(['roll_type'=>'card_four','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
            $error = '您没有饭票，抢单失败';
            if (!$roll) {
                $this->error($error);
            }
            if (isset($_SERVER['HTTP_PLATFORM']) && in_array($_SERVER['HTTP_PLATFORM'], ['wxOfficialAccount','H5'])) {
                $play = Db::name('mtofficial')->where(['no'=>urlencode($play_no)])->order('id DESC')->find();
            } else {
                $play = Db::name('mtofficial')->where(['no'=>$play_no])->order('id DESC')->find();
            }
            if (!$play || !$play['content']) {
                $this->error('活动不存在');
            }
            $content = json_decode($play['content'],1);
            //下单操作
            Db::startTrans();
            try {
                $orderData = [
                    'user_id' => $userId,
                    'shop_no' => $play['no'],
                    'play_no' => $play['no'],
                    'shop_name' => $content['name'],
                    // 'platform_no' => isset($shop_platform['platform_no'])?$shop_platform['platform_no']:'',
                    // 'rebate_amt' => $play['shop_settlement'], // 商户要支付的返点金额
                    // 'service_charge_amt' => $play['service_amt'], // 平台手续费金额
                    'actual_rebate_amt' => $play['back_money'], // 实际用户得到的返点金额
                    'user_pay' => $play['user_pay'], // 满多少
                    'place_time' => time(),
                    'expire_time' => time() + intval(config('sn_expire')),  // 上传单号的过期时间
                    'create_by' => $userId,
                    'location' => $address,
                    'is_yunzhan' => $content['source'],
                    'proposal' => $play['content'],
                ];
                $bwc = new \services\BwcService();
                $res = $bwc->apply($poiEventId,$this->lat,$this->lng,$this->auth->mobile);
                \think\Log::write('活动报名exception1=>'.$res);
                // $res = '{"status":true,"code":200,"message":"success","data":{"order_sn": "M240409193237L45061"}}';
                $decode = json_decode($res,1);
                if ($decode['message']!='success') {
                    $this->error($decode['message']);
                } elseif (!isset($decode['data']['order_sn'])) {
                    $this->error('报名失败');
                } else {
                    $orderData['yunzhan_order_no'] = $decode['data']['order_sn'];
                }
                foreach ($content['plan_list'] as $valuess) {
                    if ($poiEventId==$valuess['plan_id']) {
                        $orderData['crood_type'] = $poiEventId;
                        $orderData['user_pay'] = $valuess['min_amount'];
                        $orderData['rebate_amt'] = $valuess['commission'];
                        $orderData['service_charge_amt'] = config('play.service_amt');
                        $orderData['actual_rebate_amt'] = round($orderData['rebate_amt']-$orderData['service_charge_amt'],2);
                    }
                }
                $order = (new \app\common\model\Order());
                $order->data($orderData)->allowField(true)->save();
                $order['proof'] = [];
                // orderlog
                OrderLog::create([
                    'play_order_id' => $order['id'],
                    // 'play_order_no' => $orderData['yunzhan_order_no'],
                    'create_by' => $this->auth->nickname,
                    'create_by_id' => $userId,
                    'is_front' => 1,
                    'info' => '报名',
                ]);
                // 消耗优惠券
                $res = \app\common\model\UserRollLog::useRoll($roll,$play['no']);
                if (!$res) {
                    Db::rollback();
                    $this->error('消耗优惠券失败');
                }
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                \think\Log::write('活动报名exception=>'.$exception->getMessage());
                $this->error('活动报名失败');
            }
        } else {
            $play_no = input('play_no', '');
            $play = (new \app\admin\model\Play())->where('play_no', $play_no)->find();
            // 是否有大牌专享券
            $play_label = 0;
            $config = config('site.play_label');
            if (count($config)) {
                foreach ($config as $keys => $values) {
                    if ($values=='大牌专享') {
                        $play_label = $keys;
                    }
                }
            }
            $roll = [];
            // 是大牌专享活动就使用大牌专享券，否则使用饭票
            if ($play_label>0 && $play['play_label']==$play_label) {
                $roll = UserRoll::where(['roll_type'=>'card_three','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
                $error = '您没有大牌专享券，抢单失败';
            } else {
                $roll = UserRoll::where(['roll_type'=>'card_four','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
                $error = '您没有饭票，抢单失败';
            }
            if (!$roll) {
                $this->error($error);
            }
            // 是否超前抢单
            $roll2 = [];
            if ($is_leading) {
                // 是否在活动开始前30分钟
                $start_time_str = strtotime(date('Ymd').' '.$play['start_time_str']);
                if (time()<$start_time_str && time()>=$start_time_str-1800) {
                    $roll2 = UserRoll::where(['roll_type'=>'card_one','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
                    if (!$roll2) {
                        $this->error('您没有超前抢单券，抢单失败');
                    }
                } else {
                    $this->error('超前抢单券不可用，抢单失败');
                }
            }
            if (!$is_validate) { // 没有经过validateOder接口验证
                //活动检测
                $user = (new \app\common\model\User())->where(['id'=> $userId,'user_type'=>2,'status'=>'normal'])->find();
                if (!$user) $this->error('该账号暂不能报名');
                if (!$user->mobile) $this->error('请先绑定手机号');

                //活动检测
                if ($user['xzxd']==1 && $play['scheme_no']!=3) {
                    $this->error('无法参与该活动');
                }
                if (empty($play) || $play['stock'] <= 0) $this->error('活动名额已满');
                if ($play['start_date'] > time() || $play['end_date'] < time()) $this->error('不在活动时间内');
                if ($play['play_status'] != 2) $this->error('活动未开始或已完结');

                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'shop_no' => $play['shop_no'],
                    'order_status' => ['in',[1,2,-3,-5]]
                ])->count();
                if ($orderNum) {
                    $this->error('您已经报名过该店铺的活动，请先完成当前未完成的订单');
                }
                // 如果是新用户专享，只能新用户报名
                // $olduser = Db::name('play_order')->where(['user_id'=>$userId,'order_status'=>['in',[3,-6,-7,-8,-9,-4]]])->count();
                $olduser = order_count_read($userId);
                if ($play['play_label']==2 && $olduser) {
                    $this->error('您不是新用户，不能报名新用户专享活动');
                }
                // 华东师范大学(中山北路校区) 的新用户限制下单
                // if (!$olduser && $address=='华东师范大学(中山北路校区)') {
                //     $this->error('无法参与该活动');
                // }
                // 下单限制
                if ($play['times_limit']==1 && $play['jt']>1 && $play['jc']>0) {
                    // 过去几天
                    $thisday = date('Y-m-d H:i:s',strtotime(date('Ymd'))-($play['jt']-1)*86400);
                    $orderNum = (new \app\common\model\Order())->where([
                        'user_id' => $userId,
                        'shop_no' => $play['shop_no'],
                        'order_status' => ['not in', [-1, -2, -4]],
                        'create_dt' => ['>',$thisday]
                    ])->count();
                    if ($orderNum >= $play['jc']) $this->error('该活动商家限制'.$play['jt'].'天只能参加'.$play['jc'].'次');
                } elseif ($play['times_limit']==1 && $play['jt']==1 && $play['jc']>0) {
                    // 过去几天
                    $thisday = date('Y-m-d H:i:s',strtotime(date('Ymd'))-($play['jt']-1)*86400);
                    $orderNum = (new \app\common\model\Order())->where([
                        'user_id' => $userId,
                        'shop_no' => $play['shop_no'],
                        'order_status' => ['not in', [-1, -2, -4]],
                        'create_dt' => ['>',$thisday]
                    ])->count();
                    if ($orderNum >= $play['jc']) $this->error('该活动商家限制'.$play['jt'].'天只能参加'.$play['jc'].'次');
                }
                // 用户完成订单小于6单时，一天最多只能完成2单，用户完成订单大于6单时，一天最多只能完成5单
                $userorder = order_count_read($userId);
                if ($userorder<6) {
                    $orderNum = (new \app\common\model\Order())->where([
                        'user_id' => $userId,
                        'create_dt' => ['>=',date('Y-m-d',time())],
                        'order_status' => ['not in',[-1,-2,-4]]
                    ])->count();
                    if ($orderNum >= 2) $this->error('您的报名次数已用完');
                } else {
                    $orderNum = (new \app\common\model\Order())->where([
                        'user_id' => $userId,
                        'create_dt' => ['>=',date('Y-m-d',time())],
                        'order_status' => ['not in',[-1,-2,-4]]
                    ])->count();
                    if ($orderNum >= 5) $this->error('您的报名次数已用完');
                }
                // 店铺是否禁止用户下单
                $shop = Db::name('shop')->where(['shop_no'=>$play['shop_no']])->field('limited_user')->find();
                if ($shop['limited_user']) {
                    $limited_user = trim($shop['limited_user'],'|');
                    $limited_user_arr = explode('|', $limited_user);
                    if (count($limited_user_arr) && in_array($this->auth->id, $limited_user_arr)) {
                        $this->error('您已超出该店铺点餐次数上限');
                    }
                }

                // 用户是否存在未完成的异常订单和未完成的不满意反馈订单
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'order_status' => ['in',[-5,-7,-8]]
                ])->count();
                if ($orderNum) {
                    $this->error('您有未完成的订单，当前不能下单');
                }
            }
            //下单操作
            $orderService = new OrderService();
            $play_order_no = $this->generateNo(['biz_tag'=>'play_order_no','len'=>12,'int_prefix'=>6]);
            if (Db::name('play_order')->where(['play_order_no'=>$play_order_no])->find()) {
                $play_order_no = $this->generateNo(['biz_tag'=>'play_order_no','len'=>12,'int_prefix'=>6]);
            }
            $order = $orderService->createOrder($userId, $play, $play_order_no, $userId, $this->auth->nickname,$roll,$roll2,$address);
        }
        if ($order) {$this->success('报名成功', $order);}
        $this->error('报名失败1');
    }

    /**
     * 报名
     * @param OrderService $orderService
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function createOrder()
    {
        $is_validate = input('is_validate',0);
        $play_no = input('play_no', '');
        $address = input('address', '');
        $is_leading = input('is_leading/d', 0); // 是否超前抢单
        $userId = $this->auth->id;
        $play = (new \app\admin\model\Play())->where('play_no', $play_no)->find();
        // 是否有大牌专享券
        $play_label = 0;
        $config = config('site.play_label');
        if (count($config)) {
            foreach ($config as $keys => $values) {
                if ($values=='大牌专享') {
                    $play_label = $keys;
                }
            }
        }
        $roll = [];
        // 是大牌专享活动就使用大牌专享券，否则使用饭票
        if ($play_label>0 && $play['play_label']==$play_label) {
            $roll = UserRoll::where(['roll_type'=>'card_three','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
            $error = '您没有大牌专享券，抢单失败';
        } else {
            $roll = UserRoll::where(['roll_type'=>'card_four','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
            $error = '您没有饭票，抢单失败';
        }
        if (!$roll) {
            $this->error($error);
        }
        // 是否超前抢单
        $roll2 = [];
        if ($is_leading) {
            // 是否在活动开始前30分钟
            $start_time_str = strtotime(date('Ymd').' '.$play['start_time_str']);
            if (time()<$start_time_str && time()>=$start_time_str-1800) {
                $roll2 = UserRoll::where(['roll_type'=>'card_one','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
                if (!$roll2) {
                    $this->error('您没有超前抢单券，抢单失败');
                }
            } else {
                $this->error('超前抢单券不可用，抢单失败');
            }
        }
        if (!$is_validate) { // 没有经过validateOder接口验证
            //活动检测
            $user = (new \app\common\model\User())->where(['id'=> $userId,'user_type'=>2,'status'=>'normal'])->find();
            if (!$user) $this->error('该账号暂不能报名');
            if (!$user->mobile) $this->error('请先绑定手机号');

            //活动检测
            if ($user['xzxd']==1 && $play['scheme_no']!=3) {
                $this->error('无法参与该活动');
            }
            if (empty($play) || $play['stock'] <= 0) $this->error('活动名额已满');
            if ($play['start_date'] > time() || $play['end_date'] < time()) $this->error('不在活动时间内');
            if ($play['play_status'] != 2) $this->error('活动未开始或已完结');

            $orderNum = (new \app\common\model\Order())->where([
                'user_id' => $userId,
                'shop_no' => $play['shop_no'],
                'order_status' => ['in',[1,2,-3,-5]]
            ])->count();
            if ($orderNum) {
                $this->error('您已经报名过该店铺的活动，请先完成当前未完成的订单');
            }
            // 如果是新用户专享，只能新用户报名
            // $olduser = Db::name('play_order')->where(['user_id'=>$userId,'order_status'=>['in',[3,-6,-7,-8,-9,-4]]])->count();
            $olduser = order_count_read($userId);
            if ($play['play_label']==2 && $olduser) {
                $this->error('您不是新用户，不能报名新用户专享活动');
            }
            // 华东师范大学(中山北路校区) 的新用户限制下单
            // if (!$olduser && $address=='华东师范大学(中山北路校区)') {
            //     $this->error('无法参与该活动');
            // }
            // 下单限制
            if ($play['times_limit']==1 && $play['jt']>1 && $play['jc']>0) {
                // 过去几天
                $thisday = date('Y-m-d H:i:s',strtotime(date('Ymd'))-($play['jt']-1)*86400);
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'shop_no' => $play['shop_no'],
                    'order_status' => ['not in', [-1, -2, -4]],
                    'create_dt' => ['>',$thisday]
                ])->count();
                if ($orderNum >= $play['jc']) $this->error('该活动商家限制'.$play['jt'].'天只能参加'.$play['jc'].'次');
            } elseif ($play['times_limit']==1 && $play['jt']==1 && $play['jc']>0) {
                // 过去几天
                $thisday = date('Y-m-d H:i:s',strtotime(date('Ymd'))-($play['jt']-1)*86400);
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'shop_no' => $play['shop_no'],
                    'order_status' => ['not in', [-1, -2, -4]],
                    'create_dt' => ['>',$thisday]
                ])->count();
                if ($orderNum >= $play['jc']) $this->error('该活动商家限制'.$play['jt'].'天只能参加'.$play['jc'].'次');
            }
            // 用户完成订单小于6单时，一天最多只能完成2单，用户完成订单大于6单时，一天最多只能完成5单
            $userorder = order_count_read($userId);
            if ($userorder<6) {
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'create_dt' => ['>=',date('Y-m-d',time())],
                    'order_status' => ['not in',[-1,-2,-4]]
                ])->count();
                if ($orderNum >= 2) $this->error('您的报名次数已用完');
            } else {
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'create_dt' => ['>=',date('Y-m-d',time())],
                    'order_status' => ['not in',[-1,-2,-4]]
                ])->count();
                if ($orderNum >= 5) $this->error('您的报名次数已用完');
            }
            // 店铺是否禁止用户下单
            $shop = Db::name('shop')->where(['shop_no'=>$play['shop_no']])->field('limited_user')->find();
            if ($shop['limited_user']) {
                $limited_user = trim($shop['limited_user'],'|');
                $limited_user_arr = explode('|', $limited_user);
                if (count($limited_user_arr) && in_array($this->auth->id, $limited_user_arr)) {
                    $this->error('您已超出该店铺点餐次数上限');
                }
            }

            // 用户是否存在未完成的异常订单和未完成的不满意反馈订单
            $orderNum = (new \app\common\model\Order())->where([
                'user_id' => $userId,
                'order_status' => ['in',[-5,-7,-8]]
            ])->count();
            if ($orderNum) {
                $this->error('您有未完成的订单，当前不能下单');
            }
        }
        //下单操作
        $orderService = new OrderService();
        $play_order_no = $this->generateNo(['biz_tag'=>'play_order_no','len'=>12,'int_prefix'=>6]);
        if (Db::name('play_order')->where(['play_order_no'=>$play_order_no])->find()) {
            $play_order_no = $this->generateNo(['biz_tag'=>'play_order_no','len'=>12,'int_prefix'=>6]);
        }
        $order = $orderService->createOrder($userId, $play, $play_order_no, $userId, $this->auth->nickname,$roll,$roll2,$address);
        // var_dump($order);exit;
        if ($order) {$this->success('报名成功', $order);}
        $this->error('报名失败1');
    }

    /**
     * 订单详情
     * @param OrderService $orderService
     */
    public function detail(OrderService $orderService)
    {
        $id = input('id/d', 0);
        $mtofficial = input('mtofficial/d', 0);
        $source = input('source/d', 0);
        // $mtofficial = 1;
        if (!$id) {
            $this->error('缺少必要参数');
        }
        $userId = $this->auth->id;
        $shopObj = new \app\admin\model\Shop();
        $user = Db::name('user')->where('id',$this->auth->id)->field('mobile,entry_mobile')->find();
        if (!$mtofficial) {
            $where['user_id'] = $userId;
            $order = $orderService->getOrderDetail($id, $where);
            if ($order) {
                if ($order['is_yunzhan']==0) {
                    $shop = Db::name('shop')
                        ->field("*")
                        ->where('shop_no',$order['shop_no'])
                        ->find();
                    // $distance_arr = \app\api\service\PlayService::shopDistance($shop,$this->lng,$this->lat,2);
                    $shop_platform = Db::name('shop_platform')->where(['shop_no'=>$order['shop_no']])->field('qrcode_pic,platform_no,is_xls,elm_appenter')->find();
                    if (isset($shop_platform['qrcode_pic']) && $shop_platform['qrcode_pic']) {
                        $shop_platform['qrcode_pic'] = config('upload_domain').$shop_platform['qrcode_pic'];
                    }
                    $shop = array_merge($shop,$shop_platform);
                    // $distance_text = isset($distance_arr[0])?$distance_arr[0]:'0km';
                    $obj = new \app\api\service\PlayService();
                    $distance_text = $obj->get_distance([$this->lat,$this->lng],[$shop['lat'],$shop['lng']]);
                    $distance_text = $distance_text>1000?round($distance_text/1000,2).'km':$distance_text.'m';
                } else {
                    $order['play_order_no'] = $order['yunzhan_order_no'];
                    $content=[];
                    if ($order['proposal']) $content = json_decode($order['proposal'],1);
                    $order['source'] = $content['source'] = $order['is_yunzhan'];
                    list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($order['play_no'],$order['crood_type'],$content);
                    $order['play'] = $play;
                    $order['shop'] = $shop;
                    $distance_text = $play['distance_text'];
                }
                if ($order['order_status']==1 && $order['place_time']>0 && (!isset($order['proof']['wm_order_sn']) || !$order['proof']['wm_order_sn'])) {
                    $order['crood_type'] = '已报名，待下单';
                }elseif ($order['order_status']==1 && $order['place_time']>0 && isset($order['proof']['wm_order_sn']) && $order['proof']['wm_order_sn']) {
                    $order['crood_type'] = '已下单，待反馈';
                }elseif ($order['order_status']==-1 || $order['order_status']==-4) {
                    $order['crood_type'] = '已取消';
                }elseif ($order['order_status']==-5 || $order['order_status']==2) {
                    $order['crood_type'] = '待审核';
                }elseif ($order['order_status']==6) {
                    $order['crood_type'] = '待商家复审';
                }elseif ($order['order_status']==-3) {
                    $order['crood_type'] = '已驳回';
                }elseif ($order['order_status']==-2) {
                    $order['crood_type'] = '超时取消，订单关闭';
                }elseif ($order['order_status']==-6 || $order['order_status']==-7 || $order['order_status']==3) {
                    $order['crood_type'] = '已完成';
                }
            }
            if ($order) $this->success('订单详情', ['order'=>$order,'distance_text'=>$distance_text,'shop'=>$shop,'orderNum'=>empty($userId)?0:order_count_read($userId)]);
        } else {
            $Mtorder = \app\common\model\Mtorder::where('id',$id)->find();
            $order = [];
            $order['shop_no'] = $Mtorder['shop_no'];
            $order['get_coupon'] = $Mtorder['get_coupon'];
            if ($Mtorder['is_yunzhan']==0) {
                $Mtorder = \app\common\model\Mtorder::where('id',$id)->find();
                $order = [];
                $order['mtofficial'] = 1;
                $order['id'] = $Mtorder['id'];
                $order['play_order_no'] = $Mtorder['play_order_no'];
                $order['shop_name'] = $Mtorder['shop_name'];
                $order['place_time'] = $Mtorder['place_time'];
                $order['expire_time'] = $Mtorder['expire_time'];
                $order['expire_time_text'] = date('Y/m/d H:i',$Mtorder['expire_time']);
                $order['create_dt'] = $Mtorder['create_dt'];
                $order['order_status'] = $Mtorder['order_status'];
                // $mtofficial = Db::name('mtofficial')->where(['no'=>$Mtorder['play_no']])->order('id DESC')->find();
                $content = json_decode($Mtorder['content'],1);
                $order['pay_time'] = '';
                $order['user_pay'] = 0;
                $order['actual_rebate_amt'] = 0;
                if ($Mtorder['user_pay']!=0) {
                    $order['pay_time'] = date('Y/m/d H:i:s',$Mtorder['pay_time']);
                    $order['user_pay'] = $Mtorder['user_pay'];
                    $order['actual_rebate_amt'] = $Mtorder['actual_rebate_amt'];
                }
                $order['play'] = [];
                $order['play']['back_money_text'] = isset($content['coupon_text'])?$content['coupon_text']:'';
                $order['play']['img_url'] = $content['picture'];
                $order['play']['shop_name'] = $Mtorder['shop_name'];
                $order['play']['shop_type'] = 1;
                $order['play']['img'] = $content['picture'];
                $order['play']['wxPath'] = isset($content['actionUrl']['wxPath'])?$content['actionUrl']['wxPath']:'';
                $order['play']['wxAppid'] = isset($content['actionUrl']['wxAppid'])?$content['actionUrl']['wxAppid']:'';
                $platform_no = '';
                if (isset($content['actionUrl']['wxPath']) && $content['actionUrl']['wxPath']) {
                    $wxPath = explode('?', $content['actionUrl']['wxPath']);
                    if (isset($wxPath[1]) && $wxPath[1]) {
                        $path = explode('&', $wxPath[1]);
                        foreach ($path as $p) {
                            if (strpos($p,'poi_id=')!==false) {
                                $platform_no = ltrim($p,'poi_id=');
                            }
                            if (strpos($p,'poi_id_str=')!==false) {
                                $platform_no .= '&'.$p;
                            }
                        }
                    }
                }
                $order['planActivityType'] = 1;
                if ($Mtorder['cps_id'] && $content['poiEventId']!=$Mtorder['cps_id'] && isset($content['planActivityInfoList'])) {
                    foreach ($content['planActivityInfoList'] as $valuess) {
                        if ($Mtorder['cps_id']==$valuess['poiEventId']) {
                            $order['planActivityType'] = $valuess['planActivityType'];
                            $content['maxCommission'] = $valuess['maxCommission'];
                            $content['ratio'] = $valuess['ratio'];
                        }
                    }
                }
                // foreach ($content['planActivityInfoList'] as $valuess) {
                //     if ($Mtorder['cps_id']==$valuess['poiEventId']) {
                //         $content['maxCommission'] = $valuess['maxCommission'];
                //         $content['ratio'] = $valuess['ratio'];
                //     }
                // }
                $order['shop'] = [];
                $order['shop']['shop_name'] = $content['name'];
                $order['shop']['platform_no'] = $platform_no;
                $order['shop']['shop_type_text'] = '美团';
                $order['shop']['logo_pic_url'] = $content['picture'];
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                $order['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                if ($Mtorder['content']) {
                    $content2 = json_decode($Mtorder['content'],1);
                }
                if ($order['order_status']==1 && $order['place_time']>0) {
                    $order['crood_type'] = '已报名，待下单';
                } elseif ($order['order_status']==1 && $order['place_time']>0 && isset($content2['code']) && $content2['code']==3) {
                    $order['crood_type'] = '已报名，待下单';
                } elseif ($order['order_status']==1 && $order['place_time']>0 && isset($content2['code']) && $content2['code']==4) {
                    $order['crood_type'] = '已下单，待反馈';
                } elseif ($order['order_status']==4 || $order['order_status']==-5) {
                    $order['crood_type'] = '已下单';
                } elseif ($order['order_status']==-2) {
                    $order['crood_type'] = '超时取消，订单关闭';
                } elseif ($order['order_status']==-1 || $order['order_status']==-4) {
                    $order['crood_type'] = '已取消';
                } elseif ($order['order_status']==-3) {
                    $order['crood_type'] = '已驳回';
                } elseif ($order['order_status']==-6 || $order['order_status']==-7 || $order['order_status']==3) {
                    $order['crood_type'] = '已完成';
                }
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                // 驳回原因
                if ($order['proof']['handle_admin_desc']) {
                    $explode = explode('（', $order['proof']['handle_admin_desc']);
                    if (isset($explode[1]) && $explode[1]) {
                        $explode = explode('）', $explode[1]);
                    }
                    if (isset($explode[0])) {
                        $order['proof']['handle_admin_desc'] = $explode[0];
                    }
                }
                $ratio = normal_return($content['maxCommission'],$content['ratio'])*100;
                $order['ratio'] = $ratio;
                $order['maxCommission'] = max_return($content['maxCommission'],$content['ratio']);
                $order['mobile'] = $Mtorder['proposal'];
                if ($order) $this->success('订单详情', ['order'=>$order,'distance_text'=>$content['deliveryDistance'],'shop'=>$order['shop'],'orderNum'=>empty($userId)?0:order_count_read($userId)]);   
            } elseif (in_array($Mtorder['is_yunzhan'], [4,5])) {
                $content=isset($Mtorder['content'])?json_decode($Mtorder['content'],1):[];
                $order['source'] = $content['source'] = $Mtorder['is_yunzhan'];
                list($play,$shop) = (new \app\api\service\PlayService())->newmtofficial($Mtorder['play_no'],$Mtorder['cps_id'],$content);
                $content['distance'] = $play['distance_text'];
                $order['mtofficial'] = 1;
                $order['id'] = $Mtorder['id'];
                $order['play_order_no'] = $Mtorder['play_order_no'];
                $order['shop_name'] = $Mtorder['shop_name'];
                $order['place_time'] = $Mtorder['place_time'];
                $order['expire_time'] = $Mtorder['expire_time'];
                $order['expire_time_text'] = date('Y/m/d H:i',$Mtorder['expire_time']);
                $order['create_dt'] = $Mtorder['create_dt'];
                $order['order_status'] = $Mtorder['order_status'];
                if ($Mtorder['is_yunzhan']==4)  $order['shop_no'] = $Mtorder['crood_type'];
                $order['pay_time'] = '';
                $order['user_pay'] = 0;
                $order['actual_rebate_amt'] = 0;
                if ($Mtorder['user_pay']!=0) {
                    $order['pay_time'] = date('Y/m/d H:i:s',$Mtorder['pay_time']);
                    $order['user_pay'] = $Mtorder['user_pay'];
                    $order['actual_rebate_amt'] = $Mtorder['actual_rebate_amt'];
                }
                $order['play'] = $play;
                $order['planActivityType'] = $play['scheme_no']-1;
                $order['shop'] = $shop;
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                $order['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                if ($Mtorder['content']) {
                    $content2 = json_decode($Mtorder['content'],1);
                }
                if ($order['order_status']==1 && $order['pay_time']==0) {
                    $order['crood_type'] = '已报名，待下单';
                } elseif ($order['order_status']==1 && $order['pay_time']>0) {
                    $order['crood_type'] = '已下单，待反馈';
                } elseif ($order['order_status']==4 || $order['order_status']==-5) {
                    if ($order['planActivityType']==1) {
                        $order['crood_type'] = '已下单，待评价';
                    } else {
                        $order['crood_type'] = '已下单，待完成';
                    }
                } elseif ($order['order_status']==-2) {
                    $order['crood_type'] = '超时取消，订单关闭';
                } elseif ($order['order_status']==-1 || $order['order_status']==-4) {
                    $order['crood_type'] = '已取消';
                } elseif ($order['order_status']==-3) {
                    $order['crood_type'] = '已驳回';
                } elseif ($order['order_status']==-6 || $order['order_status']==-7 || $order['order_status']==3) {
                    $order['crood_type'] = '已完成';
                }
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                // 驳回原因
                if ($order['proof']['handle_admin_desc']) {
                    $explode = explode('（', $order['proof']['handle_admin_desc']);
                    if (isset($explode[1]) && $explode[1]) {
                        $explode = explode('）', $explode[1]);
                    }
                    if (isset($explode[0])) {
                        $order['proof']['handle_admin_desc'] = $explode[0];
                    }
                }
                $order['ratio'] = $play['ratio'];
                $order['maxCommission'] = $play['maxCommission'];
                if ($Mtorder['is_yunzhan']==5) {
                    $order['elmorder_num'] = Db::name('mtofficial_order')->where(['user_id'=>$this->auth->id,'order_status'=>3,'is_yunzhan'=>5])->count();
                }
            } else {
                $content=isset($Mtorder['content'])?json_decode($Mtorder['content'],1):[];
                $order['source'] = $content['source'] = $Mtorder['is_yunzhan'];
                list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($Mtorder['play_no'],$Mtorder['cps_id'],$content);
                $order['mtofficial'] = 1;
                $order['id'] = $Mtorder['id'];
                $order['play_order_no'] = $Mtorder['play_order_no'];
                $order['shop_name'] = $Mtorder['shop_name'];
                $order['place_time'] = $Mtorder['place_time'];
                $order['expire_time'] = $Mtorder['expire_time'];
                $order['expire_time_text'] = date('Y/m/d H:i',$Mtorder['expire_time']);
                $order['create_dt'] = $Mtorder['create_dt'];
                $order['order_status'] = $Mtorder['order_status'];
                // $mtofficial = Db::name('mtofficial')->where(['no'=>$Mtorder['play_no']])->order('id DESC')->find();
                $order['pay_time'] = '';
                $order['user_pay'] = 0;
                $order['actual_rebate_amt'] = 0;
                if ($Mtorder['user_pay']!=0) {
                    $order['pay_time'] = date('Y/m/d H:i:s',$Mtorder['pay_time']);
                    $order['user_pay'] = $Mtorder['user_pay'];
                    $order['actual_rebate_amt'] = $Mtorder['actual_rebate_amt'];
                }
                $order['play'] = $play;
                $order['planActivityType'] = $play['planActivityType'];
                $order['shop'] = $shop;
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                $order['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                if ($Mtorder['content']) {
                    $content2 = json_decode($Mtorder['content'],1);
                }
                if ($order['order_status']==1 && $order['pay_time']==0) {
                    $order['crood_type'] = '已报名，待下单';
                } elseif ($order['order_status']==1 && $order['pay_time']>0) {
                    $order['crood_type'] = '已下单，待反馈';
                } elseif ($order['order_status']==4 || $order['order_status']==-5) {
                    if ($order['planActivityType']==1) {
                        $order['crood_type'] = '已下单，待评价';
                    } else {
                        $order['crood_type'] = '已下单，待完成';
                    }
                } elseif ($order['order_status']==-2) {
                    $order['crood_type'] = '超时取消，订单关闭';
                } elseif ($order['order_status']==-1 || $order['order_status']==-4) {
                    $order['crood_type'] = '已取消';
                } elseif ($order['order_status']==-3) {
                    $order['crood_type'] = '已驳回';
                } elseif ($order['order_status']==-6 || $order['order_status']==-7 || $order['order_status']==3) {
                    $order['crood_type'] = '已完成';
                }
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                // 驳回原因
                if ($order['proof']['handle_admin_desc']) {
                    $explode = explode('（', $order['proof']['handle_admin_desc']);
                    if (isset($explode[1]) && $explode[1]) {
                        $explode = explode('）', $explode[1]);
                    }
                    if (isset($explode[0])) {
                        $order['proof']['handle_admin_desc'] = $explode[0];
                    }
                }
                $order['ratio'] = $play['ratio'];
                $order['maxCommission'] = $play['maxCommission'];
            }
            $order['mobile'] = $Mtorder['proposal'];
            if ($order) $this->success('订单详情', ['order'=>$order,'distance_text'=>$content['distance'],'shop'=>$order['shop'],'orderNum'=>empty($userId)?0:order_count_read($userId)]);
        }
        $this->error('订单信息获取失败');
    }

    /**
     * 订单详情
     * @param OrderService $orderService
     */
    public function detail1(OrderService $orderService)
    {
        $id = input('id/d', 0);
        $mtofficial = input('mtofficial/d', 0);
        $source = input('source/d', 0);
        // $mtofficial = 1;
        if (!$id) {
            $this->error('缺少必要参数');
        }
        $userId = $this->auth->id;
        $shopObj = new \app\admin\model\Shop();
        $user = Db::name('user')->where('id',$this->auth->id)->field('mobile,entry_mobile')->find();
        if (!$mtofficial) {
            $where['user_id'] = $userId;
            $order = $orderService->getOrderDetail($id, $where);
            if ($order) {
                if ($order['is_yunzhan']==0) {
                    $shop = Db::name('shop')
                        ->field("*")
                        ->where('shop_no',$order['shop_no'])
                        ->find();
                    $distance_arr = \app\api\service\PlayService::shopDistance($shop,$this->lng,$this->lat,2);
                    $shop_platform = Db::name('shop_platform')->where(['shop_no'=>$order['shop_no']])->field('qrcode_pic,platform_no,is_xls,elm_appenter')->find();
                    if (isset($shop_platform['qrcode_pic']) && $shop_platform['qrcode_pic']) {
                        $shop_platform['qrcode_pic'] = config('upload_domain').$shop_platform['qrcode_pic'];
                    }
                    $shop = array_merge($shop,$shop_platform);
                    $distance_text = isset($distance_arr[0])?$distance_arr[0]:'0km';
                } else {
                    $order['play_order_no'] = $order['yunzhan_order_no'];
                    $content=[];
                    if ($order['proposal']) $content = json_decode($order['proposal'],1);
                    $order['source'] = $content['source'] = $order['is_yunzhan'];
                    list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($order['play_no'],$order['crood_type'],$content);
                    $order['play'] = $play;
                    $order['shop'] = $shop;
                    $distance_text = $play['distance_text'];
                }
                if ($order['order_status']==1 && $order['place_time']>0 && (!isset($order['proof']['wm_order_sn']) || !$order['proof']['wm_order_sn'])) {
                    $order['crood_type'] = '已报名，待下单';
                }elseif ($order['order_status']==1 && $order['place_time']>0 && isset($order['proof']['wm_order_sn']) && $order['proof']['wm_order_sn']) {
                    $order['crood_type'] = '已下单，待反馈';
                }elseif ($order['order_status']==-1 || $order['order_status']==-4) {
                    $order['crood_type'] = '已取消';
                }elseif ($order['order_status']==-5 || $order['order_status']==2) {
                    $order['crood_type'] = '待审核';
                }elseif ($order['order_status']==6) {
                    $order['crood_type'] = '待商家复审';
                }elseif ($order['order_status']==-3) {
                    $order['crood_type'] = '已驳回';
                }elseif ($order['order_status']==-2) {
                    $order['crood_type'] = '超时取消，订单关闭';
                }elseif ($order['order_status']==-6 || $order['order_status']==-7 || $order['order_status']==3) {
                    $order['crood_type'] = '已完成';
                }
            }
            if ($order) $this->success('订单详情', ['order'=>$order,'distance_text'=>$distance_text,'shop'=>$shop,'orderNum'=>empty($userId)?0:order_count_read($userId)]);
        } else {
            $Mtorder = \app\common\model\Mtorder::where('id',$id)->find();
            $order = [];
            $order['shop_no'] = $Mtorder['shop_no'];
            if ($Mtorder['is_yunzhan']==0) {
                $Mtorder = \app\common\model\Mtorder::where('id',$id)->find();
                $order = [];
                $order['mtofficial'] = 1;
                $order['id'] = $Mtorder['id'];
                $order['play_order_no'] = $Mtorder['play_order_no'];
                $order['shop_name'] = $Mtorder['shop_name'];
                $order['place_time'] = $Mtorder['place_time'];
                $order['expire_time'] = $Mtorder['expire_time'];
                $order['expire_time_text'] = date('Y/m/d H:i',$Mtorder['expire_time']);
                $order['create_dt'] = $Mtorder['create_dt'];
                $order['order_status'] = $Mtorder['order_status'];
                // $mtofficial = Db::name('mtofficial')->where(['no'=>$Mtorder['play_no']])->order('id DESC')->find();
                $content = json_decode($Mtorder['content'],1);
                $order['pay_time'] = '';
                $order['user_pay'] = 0;
                $order['actual_rebate_amt'] = 0;
                if ($Mtorder['user_pay']!=0) {
                    $order['pay_time'] = date('Y/m/d H:i:s',$Mtorder['pay_time']);
                    $order['user_pay'] = $Mtorder['user_pay'];
                    $order['actual_rebate_amt'] = $Mtorder['actual_rebate_amt'];
                }
                $order['play'] = [];
                $order['play']['back_money_text'] = isset($content['coupon_text'])?$content['coupon_text']:'';
                $order['play']['img_url'] = $content['picture'];
                $order['play']['shop_name'] = $Mtorder['shop_name'];
                $order['play']['shop_type'] = 1;
                $order['play']['img'] = $content['picture'];
                $order['play']['wxPath'] = isset($content['actionUrl']['wxPath'])?$content['actionUrl']['wxPath']:'';
                $order['play']['wxAppid'] = isset($content['actionUrl']['wxAppid'])?$content['actionUrl']['wxAppid']:'';
                $platform_no = '';
                if (isset($content['actionUrl']['wxPath']) && $content['actionUrl']['wxPath']) {
                    $wxPath = explode('?', $content['actionUrl']['wxPath']);
                    if (isset($wxPath[1]) && $wxPath[1]) {
                        $path = explode('&', $wxPath[1]);
                        foreach ($path as $p) {
                            if (strpos($p,'poi_id=')!==false) {
                                $platform_no = ltrim($p,'poi_id=');
                            }
                            if (strpos($p,'poi_id_str=')!==false) {
                                $platform_no .= '&'.$p;
                            }
                        }
                    }
                }
                $order['planActivityType'] = 1;
                if ($Mtorder['cps_id'] && $content['poiEventId']!=$Mtorder['cps_id'] && isset($content['planActivityInfoList'])) {
                    foreach ($content['planActivityInfoList'] as $valuess) {
                        if ($Mtorder['cps_id']==$valuess['poiEventId']) {
                            $order['planActivityType'] = $valuess['planActivityType'];
                            $content['maxCommission'] = $valuess['maxCommission'];
                            $content['ratio'] = $valuess['ratio'];
                        }
                    }
                }
                // foreach ($content['planActivityInfoList'] as $valuess) {
                //     if ($Mtorder['cps_id']==$valuess['poiEventId']) {
                //         $content['maxCommission'] = $valuess['maxCommission'];
                //         $content['ratio'] = $valuess['ratio'];
                //     }
                // }
                $order['shop'] = [];
                $order['shop']['shop_name'] = $content['name'];
                $order['shop']['platform_no'] = $platform_no;
                $order['shop']['shop_type_text'] = '美团';
                $order['shop']['logo_pic_url'] = $content['picture'];
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                $order['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                if ($Mtorder['content']) {
                    $content2 = json_decode($Mtorder['content'],1);
                }
                if ($order['order_status']==1 && $order['place_time']>0) {
                    $order['crood_type'] = '已报名，待下单';
                } elseif ($order['order_status']==1 && $order['place_time']>0 && isset($content2['code']) && $content2['code']==3) {
                    $order['crood_type'] = '已报名，待下单';
                } elseif ($order['order_status']==1 && $order['place_time']>0 && isset($content2['code']) && $content2['code']==4) {
                    $order['crood_type'] = '已下单，待反馈';
                } elseif ($order['order_status']==4 || $order['order_status']==-5) {
                    $order['crood_type'] = '已下单';
                } elseif ($order['order_status']==-2) {
                    $order['crood_type'] = '超时取消，订单关闭';
                } elseif ($order['order_status']==-1 || $order['order_status']==-4) {
                    $order['crood_type'] = '已取消';
                } elseif ($order['order_status']==-3) {
                    $order['crood_type'] = '已驳回';
                } elseif ($order['order_status']==-6 || $order['order_status']==-7 || $order['order_status']==3) {
                    $order['crood_type'] = '已完成';
                }
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                // 驳回原因
                if ($order['proof']['handle_admin_desc']) {
                    $explode = explode('（', $order['proof']['handle_admin_desc']);
                    if (isset($explode[1]) && $explode[1]) {
                        $explode = explode('）', $explode[1]);
                    }
                    if (isset($explode[0])) {
                        $order['proof']['handle_admin_desc'] = $explode[0];
                    }
                }
                $ratio = normal_return($content['maxCommission'],$content['ratio'])*100;
                $order['ratio'] = $ratio;
                $order['maxCommission'] = max_return($content['maxCommission'],$content['ratio']);
                $order['mobile'] = $Mtorder['proposal'];
                if ($order) $this->success('订单详情', ['order'=>$order,'distance_text'=>$content['deliveryDistance'],'shop'=>$order['shop'],'orderNum'=>empty($userId)?0:order_count_read($userId)]);   
            } elseif (in_array($Mtorder['is_yunzhan'], [4,5])) {
                $content=isset($Mtorder['content'])?json_decode($Mtorder['content'],1):[];
                $order['source'] = $content['source'] = $Mtorder['is_yunzhan'];
                list($play,$shop) = (new \app\api\service\PlayService())->newmtofficial($Mtorder['play_no'],$Mtorder['cps_id'],$content);
                $content['distance'] = $play['distance_text'];
                $order['mtofficial'] = 1;
                $order['id'] = $Mtorder['id'];
                $order['play_order_no'] = $Mtorder['play_order_no'];
                $order['shop_name'] = $Mtorder['shop_name'];
                $order['place_time'] = $Mtorder['place_time'];
                $order['expire_time'] = $Mtorder['expire_time'];
                $order['expire_time_text'] = date('Y/m/d H:i',$Mtorder['expire_time']);
                $order['create_dt'] = $Mtorder['create_dt'];
                $order['order_status'] = $Mtorder['order_status'];
                // $mtofficial = Db::name('mtofficial')->where(['no'=>$Mtorder['play_no']])->order('id DESC')->find();
                $order['pay_time'] = '';
                $order['user_pay'] = 0;
                $order['actual_rebate_amt'] = 0;
                if ($Mtorder['user_pay']!=0) {
                    $order['pay_time'] = date('Y/m/d H:i:s',$Mtorder['pay_time']);
                    $order['user_pay'] = $Mtorder['user_pay'];
                    $order['actual_rebate_amt'] = $Mtorder['actual_rebate_amt'];
                }
                $order['play'] = $play;
                $order['planActivityType'] = $play['scheme_no']-1;
                $order['shop'] = $shop;
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                $order['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                if ($Mtorder['content']) {
                    $content2 = json_decode($Mtorder['content'],1);
                }
                if ($order['order_status']==1 && $order['pay_time']==0) {
                    $order['crood_type'] = '已报名，待下单';
                } elseif ($order['order_status']==1 && $order['pay_time']>0) {
                    $order['crood_type'] = '已下单，待反馈';
                } elseif ($order['order_status']==4 || $order['order_status']==-5) {
                    if ($order['planActivityType']==1) {
                        $order['crood_type'] = '已下单，待评价';
                    } else {
                        $order['crood_type'] = '已下单，待完成';
                    }
                } elseif ($order['order_status']==-2) {
                    $order['crood_type'] = '超时取消，订单关闭';
                } elseif ($order['order_status']==-1 || $order['order_status']==-4) {
                    $order['crood_type'] = '已取消';
                } elseif ($order['order_status']==-3) {
                    $order['crood_type'] = '已驳回';
                } elseif ($order['order_status']==-6 || $order['order_status']==-7 || $order['order_status']==3) {
                    $order['crood_type'] = '已完成';
                }
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                // 驳回原因
                if ($order['proof']['handle_admin_desc']) {
                    $explode = explode('（', $order['proof']['handle_admin_desc']);
                    if (isset($explode[1]) && $explode[1]) {
                        $explode = explode('）', $explode[1]);
                    }
                    if (isset($explode[0])) {
                        $order['proof']['handle_admin_desc'] = $explode[0];
                    }
                }
                $order['ratio'] = $play['ratio'];
                $order['maxCommission'] = $play['maxCommission'];
                if ($Mtorder['is_yunzhan']==5) {
                    $order['elmorder_num'] = Db::name('mtofficial_order')->where(['user_id'=>$this->auth->id,'order_status'=>3,'is_yunzhan'=>5])->count();
                }
            } else {
                $content=isset($Mtorder['content'])?json_decode($Mtorder['content'],1):[];
                $order['source'] = $content['source'] = $Mtorder['is_yunzhan'];
                list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($Mtorder['play_no'],$Mtorder['cps_id'],$content);
                $order['mtofficial'] = 1;
                $order['id'] = $Mtorder['id'];
                $order['play_order_no'] = $Mtorder['play_order_no'];
                $order['shop_name'] = $Mtorder['shop_name'];
                $order['place_time'] = $Mtorder['place_time'];
                $order['expire_time'] = $Mtorder['expire_time'];
                $order['expire_time_text'] = date('Y/m/d H:i',$Mtorder['expire_time']);
                $order['create_dt'] = $Mtorder['create_dt'];
                $order['order_status'] = $Mtorder['order_status'];
                // $mtofficial = Db::name('mtofficial')->where(['no'=>$Mtorder['play_no']])->order('id DESC')->find();
                $order['pay_time'] = '';
                $order['user_pay'] = 0;
                $order['actual_rebate_amt'] = 0;
                if ($Mtorder['user_pay']!=0) {
                    $order['pay_time'] = date('Y/m/d H:i:s',$Mtorder['pay_time']);
                    $order['user_pay'] = $Mtorder['user_pay'];
                    $order['actual_rebate_amt'] = $Mtorder['actual_rebate_amt'];
                }
                $order['play'] = $play;
                $order['planActivityType'] = $play['planActivityType'];
                $order['shop'] = $shop;
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                $order['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                if ($Mtorder['content']) {
                    $content2 = json_decode($Mtorder['content'],1);
                }
                if ($order['order_status']==1 && $order['pay_time']==0) {
                    $order['crood_type'] = '已报名，待下单';
                } elseif ($order['order_status']==1 && $order['pay_time']>0) {
                    $order['crood_type'] = '已下单，待反馈';
                } elseif ($order['order_status']==4 || $order['order_status']==-5) {
                    if ($order['planActivityType']==1) {
                        $order['crood_type'] = '已下单，待评价';
                    } else {
                        $order['crood_type'] = '已下单，待完成';
                    }
                } elseif ($order['order_status']==-2) {
                    $order['crood_type'] = '超时取消，订单关闭';
                } elseif ($order['order_status']==-1 || $order['order_status']==-4) {
                    $order['crood_type'] = '已取消';
                } elseif ($order['order_status']==-3) {
                    $order['crood_type'] = '已驳回';
                } elseif ($order['order_status']==-6 || $order['order_status']==-7 || $order['order_status']==3) {
                    $order['crood_type'] = '已完成';
                }
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                // 驳回原因
                if ($order['proof']['handle_admin_desc']) {
                    $explode = explode('（', $order['proof']['handle_admin_desc']);
                    if (isset($explode[1]) && $explode[1]) {
                        $explode = explode('）', $explode[1]);
                    }
                    if (isset($explode[0])) {
                        $order['proof']['handle_admin_desc'] = $explode[0];
                    }
                }
                $order['ratio'] = $play['ratio'];
                $order['maxCommission'] = $play['maxCommission'];
            }
            $order['mobile'] = $Mtorder['proposal'];
            if ($order) $this->success('订单详情', ['order'=>$order,'distance_text'=>$content['distance'],'shop'=>$order['shop'],'orderNum'=>empty($userId)?0:order_count_read($userId)]);
        }
        $this->error('订单信息获取失败');
    }

    /**
     * 订单详情
     * @param OrderService $orderService
     */
    public function detailbak(OrderService $orderService)
    {
        $id = input('id/d', 0);
        $mtofficial = input('mtofficial/d', 0);
        // $mtofficial = 1;
        if (!$id) {
            $this->error('缺少必要参数');
        }
        $userId = $this->auth->id;
        $user = Db::name('user')->where('id',$this->auth->id)->field('mobile,entry_mobile')->find();
        if (!$mtofficial) {
            $where['user_id'] = $userId;
            $order = $orderService->getOrderDetail($id, $where);
            if ($order) {
                $shop = Db::name('shop')
                    ->field("*")
                    ->where('shop_no',$order['shop_no'])
                    ->find();
                $distance_arr = \app\api\service\PlayService::shopDistance($shop,$this->lng,$this->lat,2);
                $shop_platform = Db::name('shop_platform')->where(['shop_no'=>$order['shop_no']])->field('qrcode_pic,platform_no')->find();
                if (isset($shop_platform['qrcode_pic']) && $shop_platform['qrcode_pic']) {
                    $shop_platform['qrcode_pic'] = config('upload_domain').$shop_platform['qrcode_pic'];
                    $shop = array_merge($shop,$shop_platform);
                }
                $distance_text = isset($distance_arr[0])?$distance_arr[0]:'0km';
                if ($order['order_status']==1 && $order['place_time']>0 && (!isset($order['proof']['wm_order_sn']) || !$order['proof']['wm_order_sn'])) {
                    $order['crood_type'] = '已报名，待下单';
                }elseif ($order['order_status']==1 && $order['place_time']>0 && isset($order['proof']['wm_order_sn']) && $order['proof']['wm_order_sn']) {
                    $order['crood_type'] = '已下单，待反馈';
                }elseif ($order['order_status']==-1 || $order['order_status']==-4) {
                    $order['crood_type'] = '已取消';
                }elseif ($order['order_status']==-5 || $order['order_status']==2) {
                    $order['crood_type'] = '待审核';
                }elseif ($order['order_status']==6) {
                    $order['crood_type'] = '待商家复审';
                }elseif ($order['order_status']==-3) {
                    $order['crood_type'] = '已驳回';
                }elseif ($order['order_status']==-2) {
                    $order['crood_type'] = '超时取消，订单关闭';
                }elseif ($order['order_status']==-6 || $order['order_status']==-7 || $order['order_status']==3) {
                    $order['crood_type'] = '已完成';
                }
            }
            if ($order) $this->success('订单详情', ['order'=>$order,'distance_text'=>$distance_text,'shop'=>$shop,'orderNum'=>empty($userId)?0:order_count_read($userId)]);
        } else {
            $Mtorder = \app\common\model\Mtorder::where('id',$id)->find();
            $order = [];
            $order['mtofficial'] = 1;
            $order['id'] = $Mtorder['id'];
            $order['play_order_no'] = $Mtorder['play_order_no'];
            $order['shop_name'] = $Mtorder['shop_name'];
            $order['place_time'] = $Mtorder['place_time'];
            $order['expire_time'] = $Mtorder['expire_time'];
            $order['expire_time_text'] = date('Y/m/d H:i',$Mtorder['expire_time']);
            $order['create_dt'] = $Mtorder['create_dt'];
            $order['order_status'] = $Mtorder['order_status'];
            // $mtofficial = Db::name('mtofficial')->where(['no'=>$Mtorder['play_no']])->order('id DESC')->find();
            $content = json_decode($Mtorder['content'],1);
            $order['pay_time'] = '';
            $order['user_pay'] = 0;
            $order['actual_rebate_amt'] = 0;
            if ($Mtorder['user_pay']!=0) {
                $order['pay_time'] = date('Y/m/d H:i:s',$Mtorder['pay_time']);
                $order['user_pay'] = $Mtorder['user_pay'];
                $order['actual_rebate_amt'] = $Mtorder['actual_rebate_amt'];
            }
            $order['play'] = [];
            $order['play']['back_money_text'] = isset($content['coupon_text'])?$content['coupon_text']:'';
            $order['play']['img_url'] = $content['picture'];
            $order['play']['shop_name'] = $Mtorder['shop_name'];
            $order['play']['shop_type'] = 1;
            $order['play']['img'] = $content['picture'];
            $order['play']['wxPath'] = isset($content['actionUrl']['wxPath'])?$content['actionUrl']['wxPath']:'';
            $order['play']['wxAppid'] = isset($content['actionUrl']['wxAppid'])?$content['actionUrl']['wxAppid']:'';
            $platform_no = '';
            if (isset($content['actionUrl']['wxPath']) && $content['actionUrl']['wxPath']) {
                $wxPath = explode('?', $content['actionUrl']['wxPath']);
                if (isset($wxPath[1]) && $wxPath[1]) {
                    $path = explode('&', $wxPath[1]);
                    foreach ($path as $p) {
                        if (strpos($p,'poi_id=')!==false) {
                            $platform_no = ltrim($p,'poi_id=');
                        }
                        if (strpos($p,'poi_id_str=')!==false) {
                            $platform_no .= '&'.$p;
                        }
                    }
                }
            }
            $order['planActivityType'] = 1;
            if ($Mtorder['cps_id'] && $content['poiEventId']!=$Mtorder['cps_id'] && isset($content['planActivityInfoList'])) {
                foreach ($content['planActivityInfoList'] as $valuess) {
                    if ($Mtorder['cps_id']==$valuess['poiEventId']) {
                        $order['planActivityType'] = $valuess['planActivityType'];
                        $content['maxCommission'] = $valuess['maxCommission'];
                        $content['ratio'] = $valuess['ratio'];
                    }
                }
            }
            // foreach ($content['planActivityInfoList'] as $valuess) {
            //     if ($Mtorder['cps_id']==$valuess['poiEventId']) {
            //         $content['maxCommission'] = $valuess['maxCommission'];
            //         $content['ratio'] = $valuess['ratio'];
            //     }
            // }
            $order['shop'] = [];
            $order['shop']['shop_name'] = $content['name'];
            $order['shop']['platform_no'] = $platform_no;
            $order['shop']['shop_type_text'] = '美团';
            $order['shop']['logo_pic_url'] = $content['picture'];
            $order['place_time_text'] = date('m/d H:i',$order['place_time']);
            $order['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
            if ($Mtorder['content']) {
                $content2 = json_decode($Mtorder['content'],1);
            }
            if ($order['order_status']==1 && $order['place_time']>0) {
                $order['crood_type'] = '已报名，待下单';
            } elseif ($order['order_status']==1 && $order['place_time']>0 && isset($content2['code']) && $content2['code']==3) {
                $order['crood_type'] = '已报名，待下单';
            } elseif ($order['order_status']==1 && $order['place_time']>0 && isset($content2['code']) && $content2['code']==4) {
                $order['crood_type'] = '已下单，待反馈';
            } elseif ($order['order_status']==4 || $order['order_status']==-5) {
                $order['crood_type'] = '已下单';
            } elseif ($order['order_status']==-2) {
                $order['crood_type'] = '超时取消，订单关闭';
            } elseif ($order['order_status']==-1 || $order['order_status']==-4) {
                $order['crood_type'] = '已取消';
            } elseif ($order['order_status']==-3) {
                $order['crood_type'] = '已驳回';
            } elseif ($order['order_status']==-6 || $order['order_status']==-7 || $order['order_status']==3) {
                $order['crood_type'] = '已完成';
            }
            $order['place_time_text'] = date('m/d H:i',$order['place_time']);
            // 驳回原因
            if ($order['proof']['handle_admin_desc']) {
                $explode = explode('（', $order['proof']['handle_admin_desc']);
                if (isset($explode[1]) && $explode[1]) {
                    $explode = explode('）', $explode[1]);
                }
                if (isset($explode[0])) {
                    $order['proof']['handle_admin_desc'] = $explode[0];
                }
            }
            $ratio = normal_return($content['maxCommission'],$content['ratio'])*100;
            $order['ratio'] = $ratio;
            $order['maxCommission'] = max_return($content['maxCommission'],$content['ratio']);
            $order['mobile'] = $Mtorder['proposal'];
            if ($order) $this->success('订单详情', ['order'=>$order,'distance_text'=>$content['deliveryDistance'],'shop'=>$order['shop'],'orderNum'=>empty($userId)?0:order_count_read($userId)]);
        }
        $this->error('订单信息获取失败');
    }

    /**
     * 提交证明
     * @param OrderService $orderService
     */
    public function proof(OrderService $orderService)
    {
        $source = input('source/d', 0);
        $play_order_no = input('play_order_no', '');
        $is_dissatisfied = input('is_dissatisfied/d', 0); // 不满意提交
        $remarks = input('remarks', ''); 
        if ($is_dissatisfied) {
            if (!$remarks) $this->error('请填写不满意原因');
            if (mb_strlen($remarks,'UTF-8')<50) $this->error('请详述不满意原因');
        }
        // var_dump($is_dissatisfied);exit;
        $userId = $this->auth->id;
        $where['user_id'] = $userId;
        if (intval($play_order_no)>0) {
            $source=0;
        } else {
            $source=2;
        }
        if ($source>0) {
            $order = OrderModel::where('yunzhan_order_no',$play_order_no)->find();
            $proof = OrderProof::where('play_order_no',$order['yunzhan_order_no'])->order('id DESC')->find();
        } else {
            $order = OrderModel::where('play_order_no',$play_order_no)->find();
            $proof = OrderProof::where('play_order_no',$order['play_order_no'])->order('id DESC')->find();
        }
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order['order_status']!=1 && $order['order_status']!=-3) {
            $this->error('订单状态有误');
        }
        if ($order['order_status']==1) {
            if (!$proof) {
                $this->error('未提交单号');
            }
            if (time()>$order['expire_time']) {
                $this->error('上传凭据超时');
            }
        }
        $proof['upload_time'] = time();
        Db::startTrans();
        try {
            // 被驳回后第二次提交
            if ($order['order_status']==-3) {
                if ($proof['handle_status']!=-1 && $proof['handle_status']!=0) {
                // if ($proof['handle_status']!=-1) {
                    $this->error('不能重复提交');
                }
                // if (OrderProof::where('play_order_no',$order['play_order_no'])->count()!=1) {
                //     $this->error('提交有误');
                // }
                // 同一订单号提交过后不可重复提交
                $snNUm = OrderModel::where([
                    'wm_order_sn'=>$proof['wm_order_sn'],
                    'order_status' => ['in',[1,2,3,-5,-6,-7,-8,-9]]
                ])->find();
                if (count($snNUm)>0) {
                    $this->error('该外卖单号已使用过');
                }
                // 新的凭据
                $OrderProof = new OrderProof();
                $data = [
                    'wm_order_sn' => $proof['wm_order_sn'],
                    'merchant_id' => $proof['merchant_id'],
                    'shop_no' => $proof['shop_no'],
                    'user_id' => $proof['user_id'],
                    'play_order_no' => $proof['play_order_no'],
                    'platform_no' => $proof['platform_no'],
                    'user_pay' => $proof['user_pay'],
                    'back_money' => $proof['back_money'],
                    'upload_time' => time(),
                    // 'machine_audit_state' => -1
                ];
                $OrderProof->allowField(true)->save($data);
                $proof = OrderProof::where('id',$OrderProof['id'])->order('id DESC')->find();
                // 之前是不是不满意反馈
                if (Db::name('play_order_log')->where(['play_order_id'=>$order['id'],'info'=>'不满意提交'])->count()) {
                    $is_dissatisfied = 1;
                }
            } 
            $data =
                [
                    'one_image' => input('img1', ''),
                    'two_image' => input('img2', ''),
                    'three_image' => input('img3', ''),
                    'remarks' => input('remarks', '')
                ];
            //验证
            $rule = [
                'one_image' => "require",
                // 'two_image' => "require",
                'remarks' => "max:150"
            ];
            $msg = [
                'one_image.require' => '请上传订单截图1',
                // 'two_image.require' => '请上传订单截图2',
                'remarks.max' => '备注过长',
            ];
            if ($_SERVER['HTTP_PLATFORM']=='App') {
                $msg = [
                    'one_image.require' => '请授权检测您的订单信息',
                    // 'two_image.require' => '请授权检测您的订单信息',
                    'remarks.max' => '备注过长',
                ];
            }
            if ($source>0) {
                list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($order['play_no'],$order['crood_type']);
            } else {
                $play = (new \app\admin\model\Play())->where(['play_no' => $order->play_no])->find();
            }
            if (!$play) {
                $this->error('未找到对应活动');
            }

            if ($play['scheme_no'] !=3) {
                // 匹配到cps数据的话不用上传订单信息截图
                if ($order['cps_id']==0 && $proof['machine_audit_state']==0) {
                    $validate = new \think\Validate($rule, $msg);
                    if (!$validate->check($data)) $this->error($validate->getError());
                }
                if ($play && in_array($play['scheme_no'],[1,2])) {
                    $rule = [
                        'three_image' => "require",
                    ];
                    $msg = [
                        'three_image.require' => '请上传用餐体验截图',
                    ];
                    $validate = new \think\Validate($rule, $msg);
                    if (!$validate->check($data)) $this->error($validate->getError());
                }
            } else {
                // 匹配到cps数据的话不用上传订单信息截图
                if ($order['cps_id']==0 && $proof['machine_audit_state']==0) {
                    $validate = new \think\Validate($rule, $msg);
                    if (!$validate->check($data)) $this->error($validate->getError());
                }
            }
            // if (!isset($data['two_image']) || !$data['two_image']) $data['two_image'] = $data['one_image'];
            // 提交渠道：1-H5，2-在线识别3-APP人工通道
            $data['platform'] = 0;
            if ($_SERVER['HTTP_PLATFORM']=='wxOfficialAccount') {
                $data['platform'] = 1;
            } elseif ($_SERVER['HTTP_PLATFORM']=='wxMiniProgram') {
                $data['platform'] = 4;
            } elseif ($_SERVER['HTTP_PLATFORM']=='App') {
                if ($data['one_image'] && $data['two_image']) { // 上传前两张图的是人工提交
                    $data['platform'] = 3;
                } elseif (in_array($proof['machine_audit_state'], [2,3])) {
                    $data['platform'] = 2;
                } else {
                    $data['platform'] = 3;
                }
            } 
            // 机审接口
            $data['machine_audit_state'] = -1;
            // 自动机审通过，机审不通过进到人工审
            $User = new \app\common\model\User();
            $user = $User->get($order['user_id']);
            // 当活动为自动审核通过且不是不满意反馈且用户不限制且返现金额小于35
            if ($play['machine_audit']==1 && !$is_dissatisfied) {
                $OcrService = new OcrService();
                $res = $OcrService->ocr1($play, $order, $proof ,$data);
                // $res=['res'=>1,'resarr'=>["订单状态"=>1,"店铺名称"=>1,"订单号"=>1,"下单时间"=>1,"实付金额"=>1,"反馈识别"=>1],'money'=>0];
                $data['actual_pay'] = isset($res['money'])&&$res['money']?$res['money']:0;
                $data['machine_audit_desc'] = json_encode($res['resarr'],JSON_UNESCAPED_UNICODE);
                if ($res['res']==1) {
                    $userorder = order_count_read($userId);
                    // 当用户有效订单小于5且不是cps和app检测订单，且无需反馈的订单类型,需要后台复审
                    if ($userorder>=5 || $data['platform']==2 || $order['cps_id']>0 || $play['scheme_no']!=3) {
                        $data['machine_audit_state'] = 1;
                    }
                }
                // 饿了么查询订单状态接口超时返回结果会覆盖已完成结果的处理
                if ($play['shop_type']==2 && $res['res']==0) {
                    if ($source>0) {
                        $order_status = OrderModel::where('yunzhan_order_no',$play_order_no)->value('order_status');
                    } else {
                        $order_status = OrderModel::where('play_order_no',$play_order_no)->value('order_status');
                    }
                    if ($order_status==3) {
                        $this->error('');
                    }
                }
            }
            // 如果匹配到cps,生成第一第二张图
            if ($order['cps_id']>0) {
                $cps = Db::name('cps')->where('id',$order['cps_id'])->find();
                if ($cps) {
                    $mb_strlen = mb_strlen($play['shop_name']);
                    if ($mb_strlen>14) {
                        $shop_name = mb_substr($play['shop_name'],0,14).'...';
                        $x = 175;
                    } else {
                        $shop_name = $play['shop_name'];
                        $x = (14-$mb_strlen)*10+175+10;
                    }
                    $arr = [
                        [$shop_name,$x,443],
                        [$cps['order_id'],205,475],
                        [$cps['pay_time'],226,507],
                        [$cps['amount'],320,539],
                    ];
                    $data['actual_pay'] = isset($cps['amount'])&&$cps['amount']?$cps['amount']:0;
                    $resimg = $orderService->buildImg($arr,$play['shop_type']);
                    if ($resimg) {
                        $data['one_image'] = $resimg;
                        $data['two_image'] = $data['one_image'];
                    }
                }
            }
            // 如果有图片的话不要覆盖空数据
            if (!$data['one_image']) {
                $data['one_image'] = $proof['one_image'];
            }
            if (!$data['two_image']) {
                $data['two_image'] = $proof['two_image'];
            }
            // 机审通过，则订单已完成
            if ($data['machine_audit_state']==1) {
                // 商家复审的情况
                $shop = Db::name('shop')->where(['shop_no'=>$order['shop_no']])->field('is_sjzp,middleman_id,shop_no,shop_type')->find();
                // 如果订单满足复审条件的同时是立即配送的就不需要复审
                $ljps = 0;
                if ($proof['machine_audit_desc']) {
                    if (strpos($proof['machine_audit_desc'],'立即配送')) $ljps = 1;
                } else {
                    if (isset($res['resarr']['立即配送'])) $ljps = 1;
                }
                $fushen_tips = is_fushen($shop['is_sjzp'],$userorder,$play['back_money'],$play['is_pay'],$user['is_limited'],$ljps,$order['create_dt'],$play['play_label'],$order['cps_id'],$shop['shop_type']);
                if ($fushen_tips) {
                    $data['handle_admin_id'] = $this->auth->id;
                    $data['handle_status'] = 1;
                    $data['handle_time'] = time();
                    $data['upload_time'] = time();
                    $data['handle_admin_desc'] = 'Admin（'.$fushen_tips.'）商家复审';
                    $proof->isUpdate(true)->save($data);
                    OrderLog::create([
                        'play_order_id' => $order->id,
                        'play_order_no' => $order->play_order_no,
                        'info' => '机审通过，待商家复审',
                        'create_by' => $this->auth->nickname,
                        'create_by_id' => $this->auth->id,
                        'is_front' => 1,
                    ]);
                    // 订单状态
                    $order->is_fushen = 1;
                    $order->order_status = 6;
                    $order->update_by = $this->auth->id;
                    $order->save();
                    if ($source==0) {
                        $complete_order = (new OrderModel())->where(['play_no'=>$order['play_no'],'order_status'=>['in',[3,6,-9]]])->count();
                        // 状态改为待支付
                        if (($complete_order==$play['num'] && $play['play_status']==2) || ($play['play_status']==4 && $complete_order==$play['num']-$play['stock'] && $play['num']-$play['stock']>0)) {
                            // 如果是前台发布的活动，此时直接完成活动,否则状态改为待支付
                            if ($play['pay_status']==3 && $play['is_pay']==1) {
                                $play->play_status = 5;
                                $play->pay_status = 2;
                                $play->last_pay_time = time();
                                $play->update_by = $this->auth->nickname;
                                $play->acture_total_money = (float)(new OrderModel())->where(['play_no'=>$play['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt+service_charge_amt)');
                                $play->save();
                                // 冻结金额减少
                                $money = -1*($play['total_money']-$play['acture_total_money']);
                                (new \app\common\model\User())->money($money, $play['user_id'], '商家结算', $play['play_no'], 1);
                                // 商家余额增加
                                $money = -1*$money;
                                (new \app\common\model\User())->money($money, $play['user_id'], '商家结算', $play['play_no']);
                                // 订单支付状态
                                (new OrderModel())->where(['play_no'=>$order['play_no'],'order_status'=>['in',[3,6,-9]]])->update(['is_pay'=>1,'pay_time'=>time()]);
                            } else {
                                $play->play_status = 3;
                                $play->acture_total_money = (float)(new OrderModel())->where(['play_no'=>$play['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt+service_charge_amt)');
                                $play->save();
                            }
                        }
                    }
                } else {
                    // 用户获得吃豆
                    $beans = $order['actual_rebate_amt'];
                    $User->beans($beans,$order['user_id'],'下单返豆',$order['play_order_no']);
                    // 实际返豆
                    $order->actual_rebate_amt = $beans;
                    // 订单状态
                    $order->order_status = 3;
                    $order->update_by = $this->auth->id;
                    $order->save();
                    //
                    $data['handle_status'] = 1;
                    $data['handle_time'] = time();
                    $data['upload_time'] = time();
                    $proof->isUpdate(true)->save($data);
                    // $this->orderLog($order->id,$order->play_order_no,'机审通过',$this->auth->nickname,$this->auth->id);
                    OrderLog::create([
                        'play_order_id' => $order->id,
                        'play_order_no' => $order->play_order_no,
                        'info' => '机审通过',
                        'create_by' => $this->auth->nickname,
                        'create_by_id' => $this->auth->id,
                        'is_front' => 1,
                    ]);
                    // 消息处理
                    // $user = $User->get($order['user_id']);
                    // 前台发布活动，当前这一单冻结金额减少
                    if ($play['is_pay']==1 && $play['pay_status']==3) {
                        // 当前这一单冻结金额减少
                        $money = -1*($order['actual_rebate_amt']+$order['service_charge_amt']);
                        (new \app\common\model\User())->money($money, $play['user_id'], '商家结算', $order['play_order_no'], 1);
                        $order->is_pay = 1;
                        $order->pay_time = time();
                        $order->save();
                    }
                    // 发送微信消息
                    $qywx = Db::name('qywx_receive')->where('user_id',$user['id'])->field('id,UserID,ExternalUserID')->find();
                    if ($qywx) {
                        $external_userid = $qywx['ExternalUserID'];
                        $sender = $qywx['UserID'];
                        $title = '您的活动订单审核成功';
                        $picurl = config('upload_domain').'/uploads/20230422/baca91c2f33a6d1270aae65ea4d3dc79.png';
                        $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                        $url = config('h5_domain').'/#/pages/index/order';
                        $lPublics = new \app\api\service\UserService();
                        $res = $lPublics->qywxPush($external_userid,$sender,$title,$picurl,$desc,$url,$user['id']);
                    }
                    // 发送app消息
                    // if (isset($user['birthday']) && $user['birthday']) {
                        $lPublics = new \app\api\service\UserService();
                        $title = '您的活动订单审核成功';
                        $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                        $url = '/pages/index/order';
                        $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id'],$order->play_order_no);
                        $title = '【完成一笔订单】任务达成';
                        $desc = '获得2次抽奖机会（当日有效）';
                        $url = '/index/raffle/raffle';
                        $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id']);
                    // }
                    if ($source==0) {
                        $complete_order = (new OrderModel())->where(['play_no'=>$order['play_no'],'order_status'=>['in',[3,6,-9]]])->count();
                        // 状态改为待支付
                        if (($complete_order==$play['num'] && $play['play_status']==2) || ($play['play_status']==4 && $complete_order==$play['num']-$play['stock'] && $play['num']-$play['stock']>0)) {
                            // 如果是前台发布的活动，此时直接完成活动,否则状态改为待支付
                            if ($play['pay_status']==3 && $play['is_pay']==1) {
                                $play->play_status = 5;
                                $play->pay_status = 2;
                                $play->last_pay_time = time();
                                $play->update_by = $this->auth->nickname;
                                $play->acture_total_money = (float)(new OrderModel())->where(['play_no'=>$play['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt+service_charge_amt)');
                                $play->save();
                                // 冻结金额减少
                                $money = -1*($play['total_money']-$play['acture_total_money']);
                                (new \app\common\model\User())->money($money, $play['user_id'], '商家结算', $play['play_no'], 1);
                                // 商家余额增加
                                $money = -1*$money;
                                (new \app\common\model\User())->money($money, $play['user_id'], '商家结算', $play['play_no']);
                                // 订单支付状态
                                (new OrderModel())->where(['play_no'=>$order['play_no'],'order_status'=>['in',[3,6,-9]]])->update(['is_pay'=>1,'pay_time'=>time()]);
                            } else {
                                $play->play_status = 3;
                                $play->acture_total_money = (float)(new OrderModel())->where(['play_no'=>$play['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt+service_charge_amt)');
                                $play->save();
                            }
                        }
                    }
                    // 分销和抽奖机会和积分
                    if ($order->order_status==3) {
                        // 中间人佣金
                        if ($play['is_pay']==1) {
                            $middleman = Db::name('middleman')->where(['id'=>$shop['middleman_id']])->field('rebate_amt,user_id')->find();
                            if (isset($middleman['rebate_amt']) && $middleman['rebate_amt']) {
                                (new \app\common\model\User())->money($middleman['rebate_amt'], $middleman['user_id'], '经纪人收益', $order['play_order_no']);
                            }
                        }
                        OrderLog::create([
                            'play_order_id' => $order->id,
                            'play_order_no' => $order->play_order_no,
                            'info' => '订单完成',
                            'create_by' => $this->auth->nickname,
                            'create_by_id' => $this->auth->id,
                            'is_front' => 1,
                        ]);
                        if ($user['pid']) {
                            $order_num = order_count($order['user_id']);
                            if ($order_num==1) {
                                $amount = (int)Db::name('config')->where('name','first_order')->value('value');
                                // 上级用户新增有效团员
                                \app\common\model\UserLuckdrawLog::addLog($user['pid'], 1, $order['play_order_no'], '新增有效团员');
                                // 如果是第一单，则上级用户获得一个有效用户，加积分
                                $res = $User->score(config('invite_score'),$user['pid'],'邀请获得');
                                if (!$res) {Db::rollback();$this->error('上级用户获取积分失败');}
                                // unipush
                                $user2 = $User->get($user['pid']);
                                // if (isset($user2['birthday']) && $user2['birthday']) {
                                    $lPublics = new \app\api\service\UserService();
                                    $title = '【新增一位有效团员】任务达成';
                                    $desc = '获得1次抽奖机会（当日有效）';
                                    $url = '/index/raffle/raffle';
                                    $res = $lPublics->pushChat($user2['birthday'],$title,$desc,$url,$user2['id']);
                                // }
                            } elseif ($order_num==2) {
                                $amount = (int)Db::name('config')->where('name','second_order')->value('value');
                            } else {
                                $rate = (int)\think\Config::get('site.third_order');
                                $amount = round($order['service_charge_amt']*$rate*0.01,2);
                                // 当前是不是会员团长
                                $user1 = \app\common\model\User::get($user['pid']);
                                if ($user1['hytz']==1) {
                                    // 团长的有效用户数是否大于指定的用户数
                                    $invitation_new_reward = \think\Config::get('site.yyty');
                                    $user_distribution = Db::name('user_distribution')->field('uid')->where(['pid'=>$user['pid'],'status'=>1])->group('uid')->select();
                                    if (count($user_distribution)>$invitation_new_reward) {
                                        $ratenim = (float)\think\Config::get('site.third_order_min3');
                                    } else {
                                        $ratenim = (float)\think\Config::get('site.third_order_min2');
                                    }
                                } else {
                                    $ratenim = (float)\think\Config::get('site.third_order_min');
                                }
                                if ($amount<$ratenim) $amount = $ratenim;
                            }
                            if ($amount) {
                                \app\common\model\UserDistribution::create([
                                    'play_order_no' => $order['play_order_no'],
                                    'uid' => $order['user_id'],
                                    'pid' => $user['pid'],
                                    'play_no' => $order['play_no'],
                                    'amount' => $amount,
                                    'order_times' => $order_num,
                                ]);
                                // 上级用户加吃豆
                                $res = $User->beans($amount, $user['pid'], '下级返利', $order['play_order_no']);
                                if (!$res) {Db::rollback();$this->error('上级返利失败');}
                                // 发送app消息
                                // $user = \app\common\model\User::get($user['pid']);
                                if (!isset($user1)) $user1 = \app\common\model\User::get($user['pid']);
                                // if (isset($user['birthday']) && $user['birthday']) {
                                    $lPublics = new \app\api\service\UserService();
                                    $title = '团长奖励获得吃豆';
                                    $desc = '您的好友'.$user['nickname'].'完成第'.$order_num.'单，奖励您'.$amount.'吃豆';
                                    $url = '/pages/user/user-data';
                                    $res = $lPublics->pushChat($user1['birthday'],$title,$desc,$url,$user1['id']);
                                // }
                            }
                        }
                        // 用户加积分
                        $res = $User->score(config('order_score'),$order['user_id'],'下单获得');
                        if (!$res) {Db::rollback();$this->error('增加积分失败');}
                        // 完成订单
                        \app\common\model\UserLuckdrawLog::addLog($order['user_id'], 1, $order['play_order_no'], '完成订单', 2);
                    }
                }
                // 云瞻活动上传凭证
                if ($order['is_yunzhan'] && in_array($order->order_status, [3,6])) {
                    $bwc = new \services\BwcService();
                    $screen_shots = '';
                    if (isset($proof['one_image'])) $screen_shots.=config('upload_domain').$proof['one_image'].',';
                    if (isset($proof['two_image'])) $screen_shots.=config('upload_domain').$proof['two_image'].',';
                    if (isset($proof['three_image'])) $screen_shots.=config('upload_domain').$proof['three_image'].',';
                    $e_commission = floatval($order['actual_rebate_amt']+$order['service_charge_amt']);
                    $actual_pay = $proof['actual_pay']==0?$order['user_pay']:$proof['actual_pay'];
                    $res = $bwc->uploadCredential($order['yunzhan_order_no'],$user['mobile'],trim($screen_shots,','),$actual_pay,$order['wm_order_sn'],$e_commission);
                    // $res='{"status":true,"code":200,"message":"success","data":true}';
                    \think\Log::write('提交凭证回调'.$res);
                    $decode = json_decode($res,1);
                    if ($decode['message']!='success') {
                        $this->error($decode['message']);
                    }
                }
                
            } else {
                $data['upload_time'] = time();
                $proof->isUpdate(true)->save($data);
                $info = '提交凭据';
                $order->order_status = 2;
                // 如果是不满意提交
                if ($is_dissatisfied) {
                    $order->order_status = -5;
                    $info = '不满意提交';
                    if ($source==0) {
                        $play->stock = $play->stock+1;
                        $play->save();
                    }
                }
                $order->save();
                // orderlog
                \app\common\model\OrderLog::create([
                    'play_order_id' => $order['id'],
                    'play_order_no' => $order['play_order_no'],
                    'create_by' => $this->auth->nickname,
                    'create_by_id' => $userId,
                    'is_front' => 1,
                    'info' => $info,
                ]);
            }
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            \think\Log::write('提交活动凭据exception=>'.$exception->getMessage());
            $this->error($exception->getMessage());
        }
        $this->success('提交成功，等待审核');
    }

    // 补充
    public function supplement(OrderService $orderService)
    {
        $play_order_no = input('play_order_no', '');
        $source = input('source/d', 0);
        if (intval($play_order_no)>0) {
            $source=0;
        } else {
            $source=2;
        }
        $userId = $this->auth->id;
        $where['user_id'] = $userId;
        if ($source) {
            $order = OrderModel::where(['yunzhan_order_no'=>$play_order_no])->find();
        } else {
            $order = OrderModel::where(['play_order_no'=>$play_order_no])->find();
        }
        if (!$order) {
            $this->error('订单不存在');
        }
        $proof = OrderProof::where('play_order_no',$order['play_order_no'])->order('id DESC')->find();
        $data =
            [
                'one_image' => input('img1', ''),
                'two_image' => input('img2', ''),
                'three_image' => input('img3', ''),
                'remarks' => input('remarks', '')
            ];
        //验证
        $rule = [
            'one_image' => "require",
            'two_image' => "require",
            'remarks' => "max:150"
        ];
        $msg = [
            'one_image.require' => '请上传订单截图1',
            'two_image.require' => '请上传订单截图2',
            'remarks.max' => '备注过长',
        ];
        $play = (new \app\admin\model\Play())->where(['play_no' => $order->play_no])->find();
        if (!$play) {
            $this->error('未找到对应活动');
        }
        // 匹配到cps数据的话不用上传订单信息截图
        if ($order['cps_id']==0) {
            $validate = new \think\Validate($rule, $msg);
            if (!$validate->check($data)) $this->error($validate->getError());
        }
        if ($play && $play->scheme_no > 1) {
            $rule['three_image'] = 'require';
            $msg['three_image.require'] = '请上传用餐体验截图';
        }

        Db::startTrans();
        try {
            $info = '我要补充';
            $supplement = json_encode($data);
            $proof->isUpdate(true)->save(['supplement'=>$supplement]);
            $order->save();

            // orderlog
            OrderLog::create([
                'play_order_id' => $order['id'],
                'play_order_no' => $order['play_order_no'],
                'create_by' => $this->auth->nickname,
                'create_by_id' => $userId,
                'is_front' => 1,
                'info' => $info,
            ]);
            Db::commit();
            $this->success('提交成功');
        } catch (Exception $exception) {
            Db::rollback();
            \think\Log::write('提交活动凭据exception=>'.$exception->getMessage());
            $this->error('提交失败');
        }
    }

    public function cancel()
    {
        $play_order_no = input('play_order_no','');
        $order = (new \app\common\model\Order())->where([
            'play_order_no' => $play_order_no,
        ])->find();
        if (empty($order)) $this->error('不可取消');
        if ($order['order_status']!=6) $this->error('不可取消');
        $order->order_status = -1;
        $order->save();


        // orderlog
        \app\common\model\OrderLog::create([
            'play_order_id' => $order['id'],
            'play_order_no' => $play_order_no,
            'create_by' => 'chbc',
            'create_by_id' => 0,
            'is_front' => 1,
            'info' => '取消订单',
        ]);
        $this->success('取消成功');
    }

    /**
     * 失败上报选项
     * @DateTime 2023-04-21T11:32:50+0800
     * @return   [type]                   [description]
     */
    public function failOptions()
    {
        $data = [
            '店铺链接无法加载',
            '复制店名搜不出来',
            '店铺小程序跳转失败',
        ];
        $this->success('',$data);
    }

    /**
     * 失败上报
     * @DateTime 2023-04-19T21:07:38+0800
     * @return   [type]                   [description]
     */
    public function fail()
    {
        $shop_no = input('shop_no','');
        $terminal = input('terminal','');
        $reason = input('reason','','htmlspecialchars');
        if (!$terminal || !$reason) {
            $this->error('缺少参数');
        }
        if (!in_array($terminal, ['ios','android','wx-web'])) {
            $this->error('参数有误');
        }
        // $order = OrderModel::where('play_order_no',$play_order_no)->find();
        // if (!$order) {
        //     $this->error('订单不存在');
        // }
        OrderFail::create([
            'terminal' => $terminal,
            'user_id' => $this->auth->id,
            // 'play_order_no' => $play_order_no,
            'reason' => $reason,
            'user_nickname' => $this->auth->nickname,
            'shop_no' => $shop_no,
        ]);
        $this->success('提交成功');
    }

    public function verifyNum()
    {
        $num = (new \app\common\model\Order())->where([
            'user_id' => $this->auth->id,
            'order_status' => 1
        ])->count();
        $this->success('', (int)$num);
    }

    /**
     * 延时券使用，延时半小时
     * @DateTime 2023-04-12T21:24:05+0800
     * @param    string                   $value [description]
     */
    public function delayedOrder()
    {
        $num = input('num/d',1);
        $play_order_no = input('play_order_no', '');
        $source = input('source/d', 0);
        $is_meituan = input('is_meituan',0);  // 是否是美团官方订单
        $roll = UserRoll::where(['roll_type'=>'card_two','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('id ASC')->limit($num)->select();
        if (count($roll)<$num) {
            $this->error('您的延时券数量不足，延时失败');
        }
        if (!$is_meituan) {
            if ($source) {
                $order = OrderModel::where(['yunzhan_order_no'=>$play_order_no,'user_id'=>$this->auth->id])->find();
            } else {
                $order = OrderModel::where(['play_order_no'=>$play_order_no,'user_id'=>$this->auth->id])->find();
            }
            if (!$order) {
                $this->error('订单不存在');
            }
            if ($order['order_status']!=1) {
                $this->error('订单状态有误');
            }
            Db::startTrans();
            // try {
                if (!$order->wm_order_sn) {
                    $order->expire_time = $order->expire_time+intval(1800*$num);
                    $order->save();
                }
                // 消耗优惠券
                $res = \app\common\model\UserRollLog::useRolls($roll,$order['play_no']);
                if (!$res) {
                    Db::rollback();
                    $this->error('用券失败');
                }
                Db::commit();
            // } catch (\Exception $e) {
            //     Db::rollback();
            //     $this->error('请求失败');
            // }
                $this->success('请求成功');
        } else {
            $order = \app\common\model\Mtorder::where(['play_order_no'=>$play_order_no,'user_id'=>$this->auth->id])->find();
            if (!$order) {
                $this->error('订单不存在');
            }
            if ($order['order_status']!=1) {
                $this->error('订单状态有误');
            }
            // 过期时间最晚到第二天0点
            $dayend = strtotime(date('Ymd'))+86399;
            if ($order->expire_time+1800>$dayend) {
                $this->error('不需要使用优惠券');
            }
            Db::startTrans();
            // try {
                $order->expire_time = $order->expire_time+intval(1800*$num);
                if ($order->expire_time>$dayend) {
                    $order->expire_time=$dayend;
                }
                if ($source==5) {
                    if ($order->expire_time-$order->place_time>7200) {
                        $this->error('此订单延时次数已使用');
                    }
                    $order->expire_time = $order->expire_time+3600;
                }
                $order->save();
                // 消耗优惠券
                $res = \app\common\model\UserRollLog::useRolls($roll,$order['play_no']);
                if (!$res) {
                    Db::rollback();
                    $this->error('用券失败');
                }
                Db::commit();
            // } catch (\Exception $e) {
            //     Db::rollback();
            //     $this->error('请求失败');
            // }
                $this->success('请求成功');
        }
    }

    /**
     * 领优惠券延时
     * @DateTime 2023-05-12T21:50:48+0800
     * @return   [type]                   [description]
     */
    public function delayedOrder2()
    {
        $play_order_no = input('play_order_no', '');
        $source = input('source/d', 0);
        $is_meituan = input('is_meituan',0);  // 是否是美团官方订单
        if ($is_meituan!=1) {
            if ($source) {
                $order = OrderModel::where(['yunzhan_order_no'=>$play_order_no,'user_id'=>$this->auth->id])->find();
            } else {
                $order = OrderModel::where(['play_order_no'=>$play_order_no,'user_id'=>$this->auth->id])->find();
            }
            if (!$order) {
                $this->error('订单不存在');
            }
            if ($order['order_status']!=1) {
                $this->error('订单状态有误');
            }
            Db::startTrans();
            try {
                if (!$order['get_coupon']) {
                    if (!$order->wm_order_sn) {
                        $order->expire_time = $order->expire_time+10800;
                    }
                    $order->get_coupon = 1;
                    $order->save();
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('请求失败');
            }
            $this->success('延时成功，已延长3小时');
        } else {
            $order = \app\common\model\Mtorder::where(['play_order_no'=>$play_order_no,'user_id'=>$this->auth->id])->find();
            if (!$order) {
                $this->error('订单不存在');
            }
            if ($order['order_status']!=1) {
                $this->error('订单状态有误');
            }
            if ($order['is_yunzhan']==1 || $order['is_yunzhan']==4) {
                $this->error('根据最新规则，当前活动无法延时');
            }
            Db::startTrans();
            // try {
                if ($source==5) {
                    if ($order->expire_time-$order->place_time>7200) {
                        $this->error('此订单延时次数已使用');
                    }
                    $order->expire_time = $order->expire_time+3600;
                } else {
                    // 过期时间第二天0点
                    $dayend = strtotime(date('Ymd'))+86399;
                    $order->expire_time = $dayend;
                }
                $order->get_coupon = 1;
                $order->save();
                Db::commit();
            // } catch (\Exception $e) {
            //     Db::rollback();
            //     $this->error('请求失败');
            // }
            if ($source==5) {
                $this->success('延时成功，已延长1小时');
            } else {
                $this->success('延时成功，已延长至23点59分');
            }
        }
    }

    /**
     * 校验cps订单的状态
     * @DateTime 2023-05-18T20:49:13+0800
     * @return   [type]                   [description]
     */
    public function checkCpsStatus()
    {
        $user_id = $this->auth->id;
        $play_order_no = input('play_order_no','');
        if (intval($play_order_no)>0) {
            $source=0;
        } else {
            $source=2;
        }
        if ($source==0) {
            $order = OrderModel::where('play_order_no',$play_order_no)->find();
        } else {
            $order = OrderModel::where('yunzhan_order_no',$play_order_no)->find();
        }
        $order['proof'] = OrderProof::where('play_order_no',$play_order_no)->order('id desc')->field('*')->find();
        $play = (new \app\admin\model\Play())->where('play_no', $order['play_no'])->find();
        if ($play['shop_type']==1) {
            $appkey=config('meituan.appkey');
            $appsecret=config('meituan.appsecret');
            $mtid=config('meituan.mtid');
            $sid=config('meituan.sid');
            $requestId = rand(1000,9999).time();
            $Obj = new \services\MeituanService($appkey,$appsecret);
            $param = [
              'page' => 1,
              'size' => 20,
              'orderId' => $order['proof']['wm_order_sn'],
              // 'businessLine' => [7],
            ];
            $res = $Obj->getCpsOrderList($param,$requestId);
            $res = json_decode($res,1);
            if (isset($res['code']) && $res['code']==0) {
                foreach ($res['data']['dataList'] as $key => $value) {
                    $value['productName'] = str_replace('（', '(', $value['productName']);
                    $value['productName'] = str_replace('）', ')', $value['productName']);
                    $value['productName'] = str_replace(' ', '', $value['productName']);
                    $play['shop_name'] = str_replace('（', '(', $play['shop_name']);
                    $play['shop_name'] = str_replace('）', ')', $play['shop_name']);
                    $play['shop_name'] = str_replace(' ', '', $play['shop_name']);
                    if (!in_array($value['status'], [3]) ) {//1-已支付，2-已核销
                        $this->success('订单状态未完成',['status'=>0,'text'=>'当前未识别到您的订单状态']);
                    }
                    // 查看cps表有没有记录，如果没有要加上
                    Db::startTrans();
                    try {
                        $proof = OrderProof::where('play_order_no',$play_order_no)->order('id desc')->field('wm_order_sn')->find();
                        if ($proof['wm_order_sn']==$value['orderId']) {
                            $proof->actual_pay=isset($value['payPrice'])&&$value['payPrice']?$value['payPrice']:0;
                            $proof->save();
                        }
                        if (!Db::name('cps')->where(['order_id'=>$value['orderId']])->count()) {
                            $all['order_id'] = $value['orderId'];
                            $all['amount'] = $value['payPrice'];
                            //status-2：付款（如果是CPA订单则表示奖励已创建） 3：完成 4：取消 5：风控 6：结算
                            if ($value['status']==2) {
                                $all['status'] = 1;
                            } elseif ($value['status']==3) {
                                $all['status'] = 2;
                            } elseif ($value['status']==6) {
                                $all['status'] = 3;
                            } else {
                                $all['status'] = $value['status'];
                            }
                            $all['shop_name'] = $value['productName'];
                            $all['pay_time'] = date('Y-m-d H:i:s',$value['payTime']);
                            $all['createtime'] = time();
                            $all['content'] = json_encode($value);
                            $all['type'] = 1;
                            $insert_id = Db::name('cps')->insertGetId($all);
                            $time = $value['payTime'];
                            $place_time = strtotime(date('Y-m-d H',$order['place_time']).':00:00');
                            if ($play['shop_name']==$value['productName'] && $value['payPrice']>=$play['user_pay'] && !$order['cps_id'] && $time>=$place_time) {
                                Db::name('play_order')->where('play_order_no',$play_order_no)->update([
                                    'cps_id'=>$insert_id,
                                    'update_dt'=>date('Y-m-d H:i:s',time()),
                                    'update_by'=>$user_id,
                                ]);
                            }
                        } else {
                            $cps = Db::name('cps')->where(['order_id'=>$value['orderId']])->find();
                            $time = $value['payTime'];
                            $place_time = strtotime(date('Y-m-d H',$order['place_time']).':00:00');
                            if ($play['shop_name']==$value['productName'] && $value['payPrice']>=$play['user_pay'] && !$order['cps_id'] && $time>=$place_time) {
                                Db::name('play_order')->where('play_order_no',$play_order_no)->update([
                                    'cps_id'=>$cps['id'],
                                    'update_dt'=>date('Y-m-d H:i:s',time()),
                                    'update_by'=>$user_id,
                                ]);
                            }
                        }
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->success('数据操作失败，请重试或联系客服',['status'=>0]);
                    }
                    $time = $value['payTime'];
                    $place_time = strtotime(date('Y-m-d H',$order['place_time']).':00:00');
                    if ($value['orderId']==$order['proof']['wm_order_sn'] && $value['productName']==$play['shop_name'] && $value['payPrice']>=$order['user_pay'] && $time>=$place_time) {
                        if ($play['scheme_no']==3) {
                            $this->success('订单完成（无需反馈）',['status'=>1,'text'=>'订单检测识别成功']);
                        } else {
                            $this->success('订单已完成（需要反馈）',['status'=>1,'text'=>'订单检测识别成功']);
                        }
                    } else {
                        $this->success('识别的订单状态（实付未满、时间不对......）',['status'=>0,'text'=>'当前未识别到您的订单状态']);
                    }
                }
            } else {
                $this->success('没有识别到订单编号',['status'=>0,'text'=>'当前未识别到您的订单状态']);
            }
        } else {
            $Obj = new \services\ElemService();
            $param = [
              'biz_unit'=>2, //1-CPA 2-CPS
              'page_size'=>20,
              'page_number'=>1,
              // 'start_date' => date('Y-m-d H:i:s',$order['place_time']),
              'start_date' => date('Y-m-d H:i:s',time()-86400),
              'end_date' => date('Y-m-d H:i:s'),
              'date_type' => 1, //时间维度，1-付款时间 2-创建时间 3-结算时间 4-更新时间
              'order_id' => $order['proof']['wm_order_sn'],
              // 'order_id' => '8037630079525584175',
            ];
            $res = $Obj->getOrderList($param);
            $res = json_decode($res,1);
            if (isset($res['alibaba_alsc_union_kbcpx_positive_order_get_response']['result']['order_detail_report_d_t_o']) && $res['alibaba_alsc_union_kbcpx_positive_order_get_response']['result']['order_detail_report_d_t_o']) {
                if (count($res['alibaba_alsc_union_kbcpx_positive_order_get_response']['result']['order_detail_report_d_t_o'])>1){
                    $this->success('没有识别到订单编号',['status'=>0,'text'=>'当前未识别到您的订单状态']);
                }
                foreach ($res['alibaba_alsc_union_kbcpx_positive_order_get_response']['result']['order_detail_report_d_t_o'] as $key => $value) {
                    $value['shop_name'] = str_replace('（', '(', $value['shop_name']);
                    $value['shop_name'] = str_replace('）', ')', $value['shop_name']);
                    $value['shop_name'] = str_replace(' ', '', $value['shop_name']);
                    $play['shop_name'] = str_replace('（', '(', $play['shop_name']);
                    $play['shop_name'] = str_replace('）', ')', $play['shop_name']);
                    $play['shop_name'] = str_replace(' ', '', $play['shop_name']);
                    if (!in_array($value['order_state'], [4])) {//2已付款，4已收货
                        $this->success('订单状态未完成',['status'=>0,'text'=>'当前未识别到您的订单状态']);
                    }
                    // 查看cps表有没有记录，如果没有要加上
                    Db::startTrans();
                    try {
                        $proof = OrderProof::where('play_order_no',$play_order_no)->order('id desc')->field('wm_order_sn')->find();
                        if ($proof['wm_order_sn']==$value['biz_order_id']) {
                            $proof->actual_pay=isset($value['pay_amount'])&&$value['pay_amount']?$value['pay_amount']:0;
                            $proof->save();
                        }
                        if (!Db::name('cps')->where(['order_id'=>$value['biz_order_id']])->count()) {
                            $all['order_id'] = $value['biz_order_id'];
                            $all['amount'] = $value['pay_amount'];
                            $all['status'] = $value['order_state'];//0已失效，1已下单，2已付款，3售中退，4已收货，5售后退
                            $all['shop_name'] = $value['shop_name'];
                            $all['pay_time'] = $value['pay_time'];
                            $all['createtime'] = time();
                            $all['content'] = json_encode($value);
                            $all['type'] = 3;
                            $insert_id = Db::name('cps')->insertGetId($all);
                            $time = strtotime($value['pay_time']);
                            $place_time = strtotime(date('Y-m-d H',$order['place_time']).':00:00');
                            if ($play['shop_name']==$value['shop_name'] && $value['pay_amount']>=$play['user_pay'] && !$order['cps_id'] && $time>=$place_time) {
                                Db::name('play_order')->where('play_order_no',$play_order_no)->update([
                                    'cps_id'=>$insert_id,
                                    'update_dt'=>date('Y-m-d H:i:s',time()),
                                    'update_by'=>$user_id,
                                ]);
                            }
                        } else {
                            $cps = Db::name('cps')->where(['order_id'=>$value['biz_order_id']])->find();
                            $time = strtotime($value['pay_time']);
                            $place_time = strtotime(date('Y-m-d H',$order['place_time']).':00:00');
                            if ($play['shop_name']==$value['shop_name'] && $value['pay_amount']>=$play['user_pay'] && !$order['cps_id'] && $time>=$place_time) {
                                Db::name('play_order')->where('play_order_no',$play_order_no)->update([
                                    'cps_id'=>$cps['id'],
                                    'update_dt'=>date('Y-m-d H:i:s',time()),
                                    'update_by'=>$user_id,
                                ]);
                            }
                        }
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->success('数据操作失败，请重试或联系客服',['status'=>0]);
                    }
                    $time = strtotime($value['pay_time']);
                    $place_time = strtotime(date('Y-m-d H',$order['place_time']).':00:00');
                    if ($value['biz_order_id']==$order['proof']['wm_order_sn'] && $value['shop_name']==$play['shop_name'] && $value['pay_amount']>=$order['user_pay'] && $time>=$place_time) {
                        if ($play['scheme_no']==3) {
                            $this->success('订单完成（无需反馈）',['status'=>1,'text'=>'订单检测识别成功']);
                        } else {
                            $this->success('订单已完成（需要反馈）',['status'=>1,'text'=>'订单检测识别成功']);
                        }
                    } else {
                        $this->success('识别的订单状态（实付未满、时间不对......）',['status'=>0,'text'=>'当前未识别到您的订单状态']);
                    }
                }
            } else {
                $this->success('没有识别到订单编号',['status'=>0,'text'=>'当前未识别到您的订单状态']);
            }
        }
        $this->success('不存在cps订单或状态不合格',['status'=>0]);
    }

    /**
     * 修改外卖订单号
     * @param string $value [description]
     */
    public function updateWmordersn()
    {
        $source = input('source/d', 0);
        $wm_order_sn = input('wm_order_sn', '','htmlspecialchars,htmlentities');
        $wm_order_sn = trim($wm_order_sn);
        $wm_order_sn = str_replace(' ', '', $wm_order_sn);  // 当前平台订单id
        if (!$wm_order_sn) {
            $this->error('请上传正确单号');
        }
        if (!is_numeric($wm_order_sn) || !\think\Validate::is($wm_order_sn, '\S{18,30}')) {
            $this->error('单号格式不对');
        }

        $play_order_no = input('play_order_no', '','htmlspecialchars,htmlentities'); 
        if (intval($play_order_no)>0) {
            $source=0;
        } else {
            $source=2;
        }
        if ($source) {
            $order = OrderModel::where(['yunzhan_order_no'=>$play_order_no,'user_id'=>$this->auth->id])->find();
        } else {
            $order = OrderModel::where(['play_order_no'=>$play_order_no,'user_id'=>$this->auth->id])->find();
        }
        if (!$order) {
            $this->error('订单不存在');
        }
        if (!$order['wm_order_sn']) $this->error('请先上传单号');
        if (!in_array($order['order_status'], [1,2,-5,6,-3])) {
            $this->error('订单状态有误');
        }
        // 同一订单号提交过后不可重复提交
        $snNUm = OrderModel::where([
            'wm_order_sn'=>$wm_order_sn,
            'order_status' => ['in',[1,2,3,6,-3,-5,-6,-7,-8,-9]]
        ])->find();
        if (count($snNUm)>0) {
            $this->error('该外卖单号已使用过');
        }
        Db::startTrans();
        try {
            $order->wm_order_sn = $wm_order_sn;
            $order->save();
            $OrderProof = OrderProof::where(['play_order_no'=>$play_order_no])->order('id DESC')->find();
            $OrderProof->wm_order_sn = $wm_order_sn;
            $OrderProof->save();
            // orderlog
            OrderLog::create([
                'play_order_id' => $order['id'],
                'play_order_no' => $order['play_order_no'],
                'create_by' => $this->auth->nickname,
                'create_by_id' => $this->auth->id,
                'is_front' => 1,
                'info' => '修改单号',
            ]);
            Db::commit();
            $this->success('修改单号成功');
        } catch (Exception $e) {
            \think\Log::write('修改单号：Exception=>'.$e->getMessage(), 'error');
            Db::rollback();
            $this->error('修改单号失败');
        }   
    }
}